<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 */

namespace Sso\WebserviceBundle\Services\UserGroup\Update\Request;

use Sso\WebserviceBundle\Services\ApiVersionInflectorInterface;
use Sso\WebserviceBundle\Services\UserGroup\Update\RequestParserInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class RequestParserFactory
{
    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * @var ApiVersionInflectorInterface
     */
    private $versionInflector;

    /**
     * RequestParserFactory constructor.
     * @param ContainerInterface $container
     * @param ApiVersionInflectorInterface $versionInflector
     */
    public function __construct(ContainerInterface $container, ApiVersionInflectorInterface $versionInflector)
    {
        $this->container = $container;
        $this->versionInflector = $versionInflector;
    }

    /**
     * @return RequestParserInterface
     */
    public function createRequestParser(): RequestParserInterface
    {
        $serviceId = $this->versionInflector->inflectService(
            'sso_webservice.services_user_group_update_request',
            'request_parser'
        );

        try {
            $requestParser = $this->container->get($serviceId);
        } catch (\Exception $e) {
            throw new \InvalidArgumentException(
                'Service ' . $serviceId . ' does not exist!'
            );
        }

        if (!$requestParser instanceof RequestParserInterface) {
            throw new \InvalidArgumentException(
                'Service ' . $serviceId . ' does not implement ' . RequestParserInterface::class . '!'
            );
        }

        return $requestParser;
    }
}
