<?php

namespace WordpressModels\DependencyInjection\Pages;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use WordpressModels\Page\AbstractPage;

/**
 * Registers all services implementing the PageInterface as tagged services.
 */
class PagesPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        if (!$container->has(PageRegistry::class)) {
            return;
        }

        $definition = $container->findDefinition(PageRegistry::class);

        // find all service IDs with the 'wpm_page' tag
        $taggedServices = $container->findTaggedServiceIds('wpm_page');

        foreach ($taggedServices as $id => $tags) {
            $serviceReflector = new \ReflectionClass($container->getDefinition($id)->getClass());
            if (!$serviceReflector->isSubclassOf(AbstractPage::class)) {
                throw new \InvalidArgumentException(sprintf('The service "%s" must extend the "%s" class.', $id, AbstractPage::class));
            }

            // add the page service to the PageRegistry service
            $definition->addMethodCall('addPage', [new Reference($id)]);
        }
    }
}