setConfigurator example



        if (isset($service['arguments'])) {
            $definition->setArguments($this->resolveServices($service['arguments']$file));
        }

        if (isset($service['properties'])) {
            $definition->setProperties($this->resolveServices($service['properties']$file));
        }

        if (isset($service['configurator'])) {
            $definition->setConfigurator($this->parseCallable($service['configurator'], 'configurator', $id$file));
        }

        if (isset($service['calls'])) {
            if (!\is_array($service['calls'])) {
                throw new InvalidArgumentException(sprintf('Parameter "calls" must be an array for service "%s" in "%s". Check your YAML syntax.', $id$file));
            }

            foreach ($service['calls'] as $k => $call) {
                if (!\is_array($call) && (!\is_string($k) || !$call instanceof TaggedValue)) {
                    throw new InvalidArgumentException(sprintf('Invalid method call for service "%s": expected map or array, "%s" given in "%s".', $id$call instanceof TaggedValue ? '!'.$call->getTag() : get_debug_type($call)$file));
                }

                
if (!class_exists(Expression::class)) {
                        throw new LogicException('Expressions cannot be used in service factories without the ExpressionLanguage component. Try running "composer require symfony/expression-language".');
                    }
                    $factory = new Expression(substr($factory, 2));
                }
                if (($factory = $this->processValue($factory)) instanceof Expression) {
                    $factory = '@='.$factory;
                }
                $value->setFactory($factory);
            }
            if (isset($changes['configurator'])) {
                $value->setConfigurator($this->processValue($value->getConfigurator()));
            }
        }

        return $value;
    }

    /** * @throws RuntimeException */
    protected function getConstructor(Definition $definition, bool $required): ?\ReflectionFunctionAbstract
    {
        
if ($constructor = $service->getAttribute('constructor')) {
            if (null !== $definition->getFactory()) {
                throw new LogicException(sprintf('The "%s" service cannot declare a factory as well as a constructor.', $service->getAttribute('id')));
            }

            $definition->setFactory([null, $constructor]);
        }

        if ($configurators = $this->getChildren($service, 'configurator')) {
            $configurator = $configurators[0];
            if ($function = $configurator->getAttribute('function')) {
                $definition->setConfigurator($function);
            } else {
                if ($childService = $configurator->getAttribute('service')) {
                    $class = new Reference($childService, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE);
                } else {
                    $class = $configurator->getAttribute('class');
                }

                $definition->setConfigurator([$class$configurator->getAttribute('method') ?: '__invoke']);
            }
        }

        
// merge in parent definition         // purposely ignored attributes: abstract, shared, tags, autoconfigured         $def->setClass($parentDef->getClass());
        $def->setArguments($parentDef->getArguments());
        $def->setMethodCalls($parentDef->getMethodCalls());
        $def->setProperties($parentDef->getProperties());
        if ($parentDef->isDeprecated()) {
            $deprecation = $parentDef->getDeprecation('%service_id%');
            $def->setDeprecated($deprecation['package']$deprecation['version']$deprecation['message']);
        }
        $def->setFactory($parentDef->getFactory());
        $def->setConfigurator($parentDef->getConfigurator());
        $def->setFile($parentDef->getFile());
        $def->setPublic($parentDef->isPublic());
        $def->setLazy($parentDef->isLazy());
        $def->setAutowired($parentDef->isAutowired());
        $def->setChanges($parentDef->getChanges());

        $def->setBindings($definition->getBindings() + $parentDef->getBindings());

        $def->setSynthetic($definition->isSynthetic());

        // overwrite with values specified in the decorator
use Symfony\Component\DependencyInjection\Loader\Configurator\ReferenceConfigurator;

trait ConfiguratorTrait
{
    /** * Sets a configurator to call after the service is fully initialized. * * @return $this */
    final public function configurator(string|array|ReferenceConfigurator $configurator)static
    {
        $this->definition->setConfigurator(static::processValue($configurator, true));

        return $this;
    }
}
if (!class_exists(Expression::class)) {
                        throw new LogicException('Expressions cannot be used in service factories without the ExpressionLanguage component. Try running "composer require symfony/expression-language".');
                    }
                    $factory = new Expression(substr($factory, 2));
                }
                if (($factory = $this->processValue($factory)) instanceof Expression) {
                    $factory = '@='.$factory;
                }
                $value->setFactory($factory);
            }
            if (isset($changes['configurator'])) {
                $value->setConfigurator($this->processValue($value->getConfigurator()));
            }
        }

        return $value;
    }

    /** * @throws RuntimeException */
    protected function getConstructor(Definition $definition, bool $required): ?\ReflectionFunctionAbstract
    {
        


    public function testAutoconfigureViaAttribute()
    {
        $container = new ContainerBuilder();
        $container->registerAttributeForAutoconfiguration(
            CustomAutoconfiguration::class,
            static function DChildDefinition $definition) {
                $definition
                    ->addMethodCall('doSomething', [1, 2, 3])
                    ->setBindings(['string $foo' => 'bar'])
                    ->setConfigurator(new Reference('my_configurator'))
                ;
            }
        );

        $container->register('my_configurator', TaggedService3Configurator::class);
        $container->register('three', TaggedService3::class)
            ->setPublic(true)
            ->setAutoconfigured(true);

        $container->compile();

        
use Symfony\Component\DependencyInjection\Loader\Configurator\ReferenceConfigurator;

trait ConfiguratorTrait
{
    /** * Sets a configurator to call after the service is fully initialized. * * @return $this */
    final public function configurator(string|array|ReferenceConfigurator $configurator)static
    {
        $this->definition->setConfigurator(static::processValue($configurator, true));

        return $this;
    }
}
new RegisterAutoconfigureAttributesPass())->process($container);

        $argument = new BoundArgument(1, false, BoundArgument::INSTANCEOF_BINDING, realpath(__DIR__.'/../Fixtures/AutoconfigureAttributed.php'));

        $expected = (new ChildDefinition(''))
            ->setLazy(true)
            ->setPublic(true)
            ->setAutowired(true)
            ->setShared(true)
            ->setProperties(['bar' => 'baz'])
            ->setConfigurator(new Reference('bla'))
            ->addTag('a_tag')
            ->addTag('another_tag', ['attr' => 234])
            ->addMethodCall('setBar', [2, 3])
            ->setBindings(['$bar' => $argument])
            ->setFactory([null, 'create'])
        ;
        $this->assertEquals([AutoconfigureAttributed::class => $expected]$container->getAutoconfiguredInstanceof());
    }

    public function testIgnoreAttribute()
    {
        
<?php
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;

$container = new ContainerBuilder();

$bar = new Definition('Bar');
$bar->setConfigurator([new Definition('Baz'), 'configureBar']);

$fooFactory = new Definition('FooFactory');
$fooFactory->setFactory([new Definition('Foobar'), 'createFooFactory']);

$container
    ->register('foo', 'Foo')
    ->setFactory([$fooFactory, 'createFoo'])
    ->setConfigurator([$bar, 'configureFoo'])
    ->setPublic(true)
;

if (isset($service['arguments'])) {
            $definition->setArguments($this->resolveServices($service['arguments']));
        }

        if (isset($service['properties'])) {
            $definition->setProperties($this->resolveServices($service['properties']));
        }

        if (isset($service['configurator'])) {
            if (is_string($service['configurator'])) {
                $definition->setConfigurator($service['configurator']);
            } else {
                $definition->setConfigurator(array($this->resolveServices($service['configurator'][0])$service['configurator'][1]));
            }
        }

        if (isset($service['calls'])) {
            if (!is_array($service['calls'])) {
                throw new InvalidArgumentException(sprintf('Parameter "calls" must be an array for service "%s" in %s. Check your YAML syntax.', $id$file));
            }

            foreach ($service['calls'] as $call) {
                
final class EnableLoggerDebugModePass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container): void
    {
        if (!$container->hasDefinition('profiler') || !$container->hasDefinition('logger')) {
            return;
        }

        $loggerDefinition = $container->getDefinition('logger');

        if (Logger::class === $loggerDefinition->getClass()) {
            $loggerDefinition->setConfigurator([__CLASS__, 'configureLogger']);
        }
    }

    public static function configureLogger(Logger $logger): void
    {
        if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) {
            $logger->enableDebug();
        }
    }
}
->addArgument($ref3 = new Reference('a'))
            ->addArgument($ref4 = new Reference('b'))
        ;

        $container
            ->register('d')
            ->setProperty('foo', $ref5 = new Reference('b'))
        ;

        $container
            ->register('e')
            ->setConfigurator([$ref6 = new Reference('b'), 'methodName'])
        ;

        $graph = $this->process($container);

        $this->assertCount(4, $edges = $graph->getNode('b')->getInEdges());

        $this->assertSame($ref1$edges[0]->getValue());
        $this->assertSame($ref4$edges[1]->getValue());
        $this->assertSame($ref5$edges[2]->getValue());
        $this->assertSame($ref6$edges[3]->getValue());
    }

    


        if (isset($service['arguments'])) {
            $definition->setArguments($this->resolveServices($service['arguments']$file));
        }

        if (isset($service['properties'])) {
            $definition->setProperties($this->resolveServices($service['properties']$file));
        }

        if (isset($service['configurator'])) {
            $definition->setConfigurator($this->parseCallable($service['configurator'], 'configurator', $id$file));
        }

        if (isset($service['calls'])) {
            if (!\is_array($service['calls'])) {
                throw new InvalidArgumentException(sprintf('Parameter "calls" must be an array for service "%s" in "%s". Check your YAML syntax.', $id$file));
            }

            foreach ($service['calls'] as $k => $call) {
                if (!\is_array($call) && (!\is_string($k) || !$call instanceof TaggedValue)) {
                    throw new InvalidArgumentException(sprintf('Invalid method call for service "%s": expected map or array, "%s" given in "%s".', $id$call instanceof TaggedValue ? '!'.$call->getTag() : get_debug_type($call)$file));
                }

                
// merge in parent definition         // purposely ignored attributes: abstract, shared, tags, autoconfigured         $def->setClass($parentDef->getClass());
        $def->setArguments($parentDef->getArguments());
        $def->setMethodCalls($parentDef->getMethodCalls());
        $def->setProperties($parentDef->getProperties());
        if ($parentDef->isDeprecated()) {
            $deprecation = $parentDef->getDeprecation('%service_id%');
            $def->setDeprecated($deprecation['package']$deprecation['version']$deprecation['message']);
        }
        $def->setFactory($parentDef->getFactory());
        $def->setConfigurator($parentDef->getConfigurator());
        $def->setFile($parentDef->getFile());
        $def->setPublic($parentDef->isPublic());
        $def->setLazy($parentDef->isLazy());
        $def->setAutowired($parentDef->isAutowired());
        $def->setChanges($parentDef->getChanges());

        $def->setBindings($definition->getBindings() + $parentDef->getBindings());

        $def->setSynthetic($definition->isSynthetic());

        // overwrite with values specified in the decorator
Home | Imprint | This part of the site doesn't use cookies.