<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Soap\ExtSoapEngine\Wsdl;

use Gls\GlsPoland\Soap\ExtSoapEngine\Wsdl\Naming\Md5Strategy;
use Gls\GlsPoland\Soap\ExtSoapEngine\Wsdl\Naming\NamingStrategy;
use Gls\GlsPoland\Soap\Wsdl\Loader\WsdlLoaderInterface;
use Symfony\Component\Filesystem\Filesystem;

final class TemporaryWsdlLoaderProvider implements WsdlProviderInterface
{
    /**
     * @var WsdlLoaderInterface
     */
    private $loader;
    /**
     * @var Filesystem
     */
    private $filesystem;
    /**
     * @var string
     */
    private $cacheDir;
    /**
     * @var NamingStrategy
     */
    private $namingStrategy;

    public function __construct(WsdlLoaderInterface $loader, Filesystem $filesystem, string $cacheDir, NamingStrategy $namingStrategy = null)
    {
        $this->loader = $loader;
        $this->filesystem = $filesystem;
        $this->cacheDir = $cacheDir;
        $this->namingStrategy = $namingStrategy ?? new Md5Strategy();
    }

    public function getWsdl(string $source): string
    {
        $file = $this->cacheDir . DIRECTORY_SEPARATOR . $this->namingStrategy->getFileName($source);
        $this->filesystem->dumpFile($file, $this->loader->load($source));

        return $file;
    }
}
