setFactory example

foreach ($container->findTaggedServiceIds('scheduler.schedule_provider') as $tags) {
            $name = $tags[0]['name'];
            $transportName = 'scheduler_'.$name;

            // allows to override the default transport registration             // in case one needs to configure it further (like choosing a different serializer)             if (isset($receivers[$transportName])) {
                continue;
            }

            $transportDefinition = (new Definition(TransportInterface::class))
                ->setFactory([new Reference('messenger.transport_factory'), 'createTransport'])
                ->setArguments(['schedule://'.$name['transport_name' => $transportName]new Reference('messenger.default_serializer')])
                ->addTag('messenger.receiver', ['alias' => $transportName])
            ;
            $container->setDefinition('messenger.transport.'.$transportName$transportDefinition);
        }
    }
}
$container->setParameter('foo.class', 'Foo');
        $container->setParameter('foo.factory.class', 'FooFactory');
        $container->setParameter('foo.arg1', 'bar');
        $container->setParameter('foo.arg2', ['%foo.arg1%' => 'baz']);
        $container->setParameter('foo.method', 'foobar');
        $container->setParameter('foo.property.name', 'bar');
        $container->setParameter('foo.property.value', 'baz');
        $container->setParameter('foo.file', 'foo.php');
        $container->setParameter('alias.id', 'bar');

        $fooDefinition = $container->register('foo', '%foo.class%');
        $fooDefinition->setFactory(['%foo.factory.class%', 'getFoo']);
        $fooDefinition->setArguments(['%foo.arg1%', ['%foo.arg1%' => 'baz']]);
        $fooDefinition->addMethodCall('%foo.method%', ['%foo.arg1%', '%foo.arg2%']);
        $fooDefinition->setProperty('%foo.property.name%', '%foo.property.value%');
        $fooDefinition->setFile('%foo.file%');
        $fooDefinition->setBindings(['$baz' => '%env(BAZ)%']);

        $container->setAlias('%alias.id%', 'foo');

        return $container;
    }
}
                        // $messageLocation = isset($tag['handles']) ? 'declared in your tag attribute "handles"' : sprintf('used as argument type in method "%s::%s()"', $r->getName(), $method);                         $messageLocation = isset($tag['handles']) ? 'declared in your tag attribute "handles"' : ($r->implementsInterface(MessageSubscriberInterface::class) ? sprintf('returned by method "%s::getHandledMessages()"', $r->getName()) : sprintf('used as argument type in method "%s::%s()"', $r->getName()$method));

                        throw new RuntimeException(sprintf('Invalid handler service "%s": class or interface "%s" '.$messageLocation.' not found.', $serviceId$message));
                    }

                    if (!$r->hasMethod($method)) {
                        throw new RuntimeException(sprintf('Invalid handler service "%s": method "%s::%s()" does not exist.', $serviceId$r->getName()$method));
                    }

                    if ('__invoke' !== $method) {
                        $wrapperDefinition = (new Definition('Closure'))->addArgument([new Reference($serviceId)$method])->setFactory('Closure::fromCallable');

                        $definitions[$definitionId = '.messenger.method_on_object_wrapper.'.ContainerBuilder::hash($message.':'.$priority.':'.$serviceId.':'.$method)] = $wrapperDefinition;
                    } else {
                        $definitionId = $serviceId;
                    }

                    $handlerToOriginalServiceIdMapping[$definitionId] = $serviceId;

                    foreach ($buses as $handlerBus) {
                        $handlersByBusAndMessage[$handlerBus][$message][$priority][] = [$definitionId$options];
                    }
                }
$factory = new AccessTokenFactory($this->createTokenHandlerFactories());
        $finalizedConfig = $this->processConfig($config$factory);

        $factory->createAuthenticator($container, 'firewall1', $finalizedConfig, 'userprovider');

        $this->assertTrue($container->hasDefinition('security.authenticator.access_token.firewall1'));
        $this->assertTrue($container->hasDefinition('security.access_token_handler.firewall1'));

        $expected = [
            'index_0' => (new ChildDefinition('security.access_token_handler.oidc_user_info.http_client'))
                ->setFactory([new Reference('oidc.client'), 'withOptions'])
                ->replaceArgument(0, ['base_uri' => 'https://www.example.com/realms/demo/protocol/openid-connect/userinfo']),
            'index_2' => 'sub',
        ];
        $this->assertEquals($expected$container->getDefinition('security.access_token_handler.firewall1')->getArguments());
    }

    /** * @dataProvider getOidcUserInfoConfiguration */
    public function testOidcUserInfoTokenHandlerConfigurationWithBaseUri(array|string $configuration)
    {
        
$value = $parameterBag->resolveValue($attribute->value);

                        if ($attribute instanceof AutowireCallable) {
                            $value = $attribute->buildDefinition($value$type$p);
                        }

                        if ($value instanceof Reference) {
                            $args[$p->name] = $type ? new TypedReference($value$type$invalidBehavior$p->name) : new Reference($value$invalidBehavior);
                        } else {
                            $args[$p->name] = new Reference('.value.'.$container->hash($value));
                            $container->register((string) $args[$p->name], 'mixed')
                                ->setFactory('current')
                                ->addArgument([$value]);
                        }

                        continue;
                    }

                    if ($type && !$p->isOptional() && !$p->allowsNull() && !class_exists($type) && !interface_exists($type, false)) {
                        $message = sprintf('Cannot determine controller argument for "%s::%s()": the $%s argument is type-hinted with the non-existent class or interface: "%s".', $class$r->name, $p->name, $type);

                        // see if the type-hint lives in the same namespace as the controller                         if (0 === strncmp($type$classstrrpos($class, '\\'))) {
                            
throw new InvalidArgumentException(sprintf('Missing attribute "package" of the "deprecated" option in "%s".', $file));
            }

            if (!isset($deprecation['version'])) {
                throw new InvalidArgumentException(sprintf('Missing attribute "version" of the "deprecated" option in "%s".', $file));
            }

            $definition->setDeprecated($deprecation['package'] ?? '', $deprecation['version'] ?? '', $deprecation['message'] ?? '');
        }

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

        if (isset($service['constructor'])) {
            if (null !== $definition->getFactory()) {
                throw new LogicException(sprintf('The "%s" service cannot declare a factory as well as a constructor.', $id));
            }

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

        if (isset($service['file'])) {
            
new CheckTypeDeclarationsPass(true))->process($container);

        $this->addToAssertionCount(1);
    }

    public function testProcessFactory()
    {
        $container = new ContainerBuilder();

        $container->register('foo', Foo::class);
        $container->register('bar', Bar::class)
            ->setFactory([
                new Reference('foo'),
                'createBar',
            ]);

        /* Asserts that the class of Bar is well detected */
        $container->register('bar_call', BarMethodCall::class)
            ->addMethodCall('setBar', [new Reference('bar')]);

        (new CheckTypeDeclarationsPass(true))->process($container);

        $this->assertInstanceOf(Bar::class$container->get('bar'));
    }
$inlinedArguments = $arguments[1]->getArguments();
        $this->assertSame($a$inlinedArguments[0]);
    }

    public function testProcessInlinesPrivateFactoryReference()
    {
        $container = new ContainerBuilder();

        $container->register('a');
        $b = $container
            ->register('b')
            ->setFactory([new Reference('a'), 'a'])
        ;

        $container
            ->register('foo')
            ->setPublic(true)
            ->setArguments([
                $ref = new Reference('b'),
            ]);

        $this->process($container);

        
public function testFactoryWithAutoconfiguredArgument()
    {
        $container = new ContainerBuilder();
        $container->register(FooTagClass::class)
            ->setPublic(true)
            ->addTag('foo_bar', ['key' => 'my_service'])
        ;
        $container->register(TaggedLocatorConsumerFactory::class);
        $container->register(TaggedLocatorConsumer::class)
            ->setPublic(true)
            ->setAutowired(true)
            ->setFactory(new Reference(TaggedLocatorConsumerFactory::class))
        ;

        $container->compile();

        /** @var TaggedLocatorConsumer $s */
        $s = $container->get(TaggedLocatorConsumer::class);

        $locator = $s->getLocator();
        self::assertSame($container->get(FooTagClass::class)$locator->get('my_service'));
    }

    

        if (null === $service && null !== $method) {
            throw new LogicException('#[AutowireCallable] attribute cannot have a $method without a $service.');
        }

        parent::__construct($callable ?? [new Reference($service)$method ?? '__invoke'], lazy: $lazy);
    }

    public function buildDefinition(mixed $value, ?string $type, \ReflectionParameter $parameter): Definition
    {
        return (new Definition($type = \is_string($this->lazy) ? $this->lazy : ($type ?: 'Closure')))
            ->setFactory(['Closure', 'fromCallable'])
            ->setArguments([\is_array($value) ? $value + [1 => '__invoke'] : $value])
            ->setLazy($this->lazy || 'Closure' !== $type && 'callable' !== (string) $parameter->getType());
    }
}
namespace Symfony\Component\DependencyInjection\Loader\Configurator\Traits;

trait ConstructorTrait
{
    /** * Sets a static constructor. * * @return $this */
    final public function constructor(string $constructor)static
    {
        $this->definition->setFactory([null, $constructor]);

        return $this;
    }
}
$this->assertEquals([['setDefaultLocale', ['fr']]]$definition->getMethodCalls());
    }

    public function testWithNonExistingSetterAndBinding()
    {
        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy": method "setLogger()" does not exist.');
        $container = new ContainerBuilder();

        $bindings = [
            '$c' => (new Definition('logger'))->setFactory('logger'),
        ];

        $definition = $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class);
        $definition->addMethodCall('setLogger');
        $definition->setBindings($bindings);

        $pass = new ResolveBindingsPass();
        $pass->process($container);
    }

    public function testSyntheticServiceWithBind()
    {
public function process(ContainerBuilder $container)
    {
        $container->setAlias(LoggerInterface::class, 'logger');

        if ($container->has('logger')) {
            return;
        }

        if ($debug = $container->getParameter('kernel.debug')) {
            // Build an expression that will be equivalent to `!in_array(PHP_SAPI, ['cli', 'phpdbg'])`             $debug = (new Definition('bool'))
                ->setFactory('in_array')
                ->setArguments([
                    (new Definition('string'))->setFactory('constant')->setArguments(['PHP_SAPI']),
                    ['cli', 'phpdbg'],
                ]);
            $debug = (new Definition('bool'))
                ->setFactory('in_array')
                ->setArguments([$debug[false]]);
        }

        $container->register('logger', Logger::class)
            ->setArguments([null, null, null, new Reference(RequestStack::class)$debug]);
    }

class ResolveFactoryClassPass extends AbstractRecursivePass
{
    protected function processValue(mixed $value, bool $isRoot = false): mixed
    {
        if ($value instanceof Definition && \is_array($factory = $value->getFactory()) && null === $factory[0]) {
            if (null === $class = $value->getClass()) {
                throw new RuntimeException(sprintf('The "%s" service is defined to be created by a factory, but is missing the factory class. Did you forget to define the factory or service class?', $this->currentId));
            }

            $factory[0] = $class;
            $value->setFactory($factory);
        }

        return parent::processValue($value$isRoot);
    }
}
'file' => 'getFile',
            'arguments' => 'getArguments',
            'properties' => 'getProperties',
            'configurator' => 'getConfigurator',
            'calls' => 'getMethodCalls',
        ] as $key => $method) {
            if ($this->definition->$method()) {
                throw new InvalidArgumentException(sprintf('The configuration key "%s" is unsupported when using "fromCallable()".', $key));
            }
        }

        $this->definition->setFactory(['Closure', 'fromCallable']);

        if (\is_string($callable) && 1 === substr_count($callable, ':')) {
            $parts = explode(':', $callable);

            throw new InvalidArgumentException(sprintf('Invalid callable "%s": the "service:method" notation is not available when using PHP-based DI configuration. Use "[service(\'%s\'), \'%s\']" instead.', $callable$parts[0]$parts[1]));
        }

        if ($callable instanceof Expression) {
            $callable = '@='.$callable;
        }

        
Home | Imprint | This part of the site doesn't use cookies.