<?php


namespace AutoAdmin\Bundle\Content\DependencyInjection\Compiler;

use AutoAdmin\Bundle\Content\Entity\Interfaces\DuplicatorInterface;
use AutoAdmin\Bundle\Content\Service\DuplicatorService;
use LogicException;
use ReflectionClass;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class DuplicatorCompilerPass implements CompilerPassInterface
{
    /**
     * @inheritDoc
     */
    public function process(ContainerBuilder $container)
    {
        $definitions = $container->findTaggedServiceIds('aa_content.duplicator');
        $duplicatorServiceDefinition = $container->findDefinition(DuplicatorService::class);

        foreach ($definitions as $id => $tags) {
            $reflection = new ReflectionClass($id);
            if (!$reflection->implementsInterface(DuplicatorInterface::class)) {
                throw new LogicException(
                    sprintf(
                        'Duplicator "%s" must implement "%s"',
                        $id,
                        DuplicatorInterface::class
                    )
                );
            }

            $duplicatorServiceDefinition->addMethodCall('addDuplicator', [new Reference($id)]);
        }
    }
}
