<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Soap\Wsdl\Loader;

use Gls\GlsPoland\Soap\Wsdl\Exception\UnloadableWsdlException;

final class StreamWrapperLoader implements WsdlLoaderInterface
{
    /**
     * This must be a valid stream context.
     *
     * @var resource|null
     */
    private $context;

    /**
     * @param resource|null $context
     */
    public function __construct($context = null)
    {
        $this->context = $context;
    }

    public function load(string $location): string
    {
        try {
            $content = \Tools::file_get_contents(
                $location,
                false,
                is_resource($this->context) ? $this->context : null
            );
        } catch (\Exception $e) {
            throw UnloadableWsdlException::fromException($e);
        }

        if (false === $content) {
            throw UnloadableWsdlException::fromLocation($location);
        }

        return $content;
    }
}
