<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\DependencyInjection\Compiler;

use Ferienpass\AdminBundle\Form\TypeGuesser\TypeGuesser;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

class FormTypeGuesserPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container): void
    {
        $taggedServices = $container->findTaggedServiceIds('ferienpass_admin.guessed_form_type');

        foreach ($taggedServices as $id => $tags) {
            foreach ($tags as $attributes) {
                if (!$attributes['class'] ?? null || !$attributes['property'] ?? null) {
                    continue;
                }

                $definition = new Definition(TypeGuesser::class, [new Reference($id), $attributes['class'], $attributes['property']]);
                $definition->addTag('form.type_guesser');

                $container->setDefinition('ferienpass_admin.form_type_guesser.'.str_replace('\\', '_', $id), $definition);
            }
        }
    }
}
