<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\CustomFieldsBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class CustomFieldCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition('chill.custom_field.provider')) {
            throw new \LogicException('service chill.custom_field.provider is not defined.');
        }

        $definition = $container->getDefinition(
            'chill.custom_field.provider'
        );

        $taggedServices = $container->findTaggedServiceIds(
            'chill.custom_field'
        );

        foreach ($taggedServices as $id => $tagAttributes) {
            foreach ($tagAttributes as $attributes) {
                $definition->addMethodCall(
                    'addCustomField',
                    [new Reference($id), $attributes['type']]
                );
            }
        }
    }
}
