setDefinition example

use Symfony\Component\DependencyInjection\ContainerBuilder;

/** * Configures a token handler from a service id. * * @see \Symfony\Bundle\SecurityBundle\Tests\DependencyInjection\Security\Factory\AccessTokenFactoryTest */
class ServiceTokenHandlerFactory implements TokenHandlerFactoryInterface
{
    public function create(ContainerBuilder $container, string $id, array|string $config): void
    {
        $container->setDefinition($idnew ChildDefinition($config));
    }

    public function getKey(): string
    {
        return 'id';
    }

    public function addConfiguration(NodeBuilder $node): void
    {
        $node->scalarNode($this->getKey())->end();
    }
}

        $builder = new ContainerBuilder();
        $definitions = [
            'foo' => new Definition('Bar\FooClass'),
            'bar' => new Definition('BarClass'),
        ];
        $builder->setDefinitions($definitions);
        $this->assertEquals($definitions$builder->getDefinitions(), '->setDefinitions() sets the service definitions');
        $this->assertTrue($builder->hasDefinition('foo'), '->hasDefinition() returns true if a service definition exists');
        $this->assertFalse($builder->hasDefinition('foobar'), '->hasDefinition() returns false if a service definition does not exist');

        $builder->setDefinition('foobar', $foo = new Definition('FooBarClass'));
        $this->assertEquals($foo$builder->getDefinition('foobar'), '->getDefinition() returns a service definition if defined');
        $this->assertSame($builder->setDefinition('foobar', $foo = new Definition('FooBarClass'))$foo, '->setDefinition() implements a fluid interface by returning the service reference');

        $builder->addDefinitions($defs = ['foobar' => new Definition('FooBarClass')]);
        $this->assertEquals(array_merge($definitions$defs)$builder->getDefinitions(), '->addDefinitions() adds the service definitions');

        try {
            $builder->getDefinition('baz');
            $this->fail('->getDefinition() throws a ServiceNotFoundException if the service definition does not exist');
        } catch (ServiceNotFoundException $e) {
            $this->assertEquals('You have requested a non-existent service "baz".', $e->getMessage(), '->getDefinition() throws a ServiceNotFoundException if the service definition does not exist');
        }

class InMemoryFactory implements UserProviderFactoryInterface
{
    /** * @return void */
    public function create(ContainerBuilder $container, string $id, array $config)
    {
        $definition = $container->setDefinition($idnew ChildDefinition('security.user.provider.in_memory'));
        $defaultPassword = new Parameter('container.build_id');
        $users = [];

        foreach ($config['users'] as $username => $user) {
            $users[$username] = ['password' => null !== $user['password'] ? (string) $user['password'] : $defaultPassword, 'roles' => $user['roles']];
        }

        $definition->addArgument($users);
    }

    /** * @return string */
$this->assertSame(TestDefinition2::class$locator('baz')::class);
    }

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

        $locator = new Definition(Locator::class);
        $locator->setPublic(true);
        $locator->addArgument(new ServiceLocatorArgument(new TaggedIteratorArgument('test_tag', null, null, true)));

        $container->setDefinition(Locator::class$locator);

        $service = new Definition(Service::class);
        $service->setPublic(true);
        $service->addTag('test_tag');

        $container->setDefinition(Service::class$service);

        $decorated = new Definition(DecoratedService::class);
        $decorated->setPublic(true);
        $decorated->setDecoratedService(Service::class);

        
// Create transitions             $transitions = [];
            $guardsConfiguration = [];
            $transitionsMetadataDefinition = new Definition(\SplObjectStorage::class);
            // Global transition counter per workflow             $transitionCounter = 0;
            foreach ($workflow['transitions'] as $transition) {
                if ('workflow' === $type) {
                    $transitionDefinition = new Definition(Workflow\Transition::class[$transition['name']$transition['from']$transition['to']]);
                    $transitionId = sprintf('.%s.transition.%s', $workflowId$transitionCounter++);
                    $container->setDefinition($transitionId$transitionDefinition);
                    $transitions[] = new Reference($transitionId);
                    if (isset($transition['guard'])) {
                        $configuration = new Definition(Workflow\EventListener\GuardExpression::class);
                        $configuration->addArgument(new Reference($transitionId));
                        $configuration->addArgument($transition['guard']);
                        $eventName = sprintf('workflow.%s.guard.%s', $name$transition['name']);
                        $guardsConfiguration[$eventName][] = $configuration;
                    }
                    if ($transition['metadata']) {
                        $transitionsMetadataDefinition->addMethodCall('attach', [
                            new Reference($transitionId),
                            
$this->assertEquals(new Reference('highest_prio_service')$refs[0]);
        $this->assertEquals(new Reference('lowest_prio_service')$refs[1]);
        $this->assertCount(4, $refs);
    }

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

        $voterDef1 = new Definition(Voter::class);
        $voterDef1->addTag('security.voter');
        $container->setDefinition('voter1', $voterDef1);

        $voterDef2 = new Definition(Voter::class);
        $voterDef2->addTag('security.voter');
        $container->setDefinition('voter2', $voterDef2);

        $container
            ->register('security.access.decision_manager', AccessDecisionManager::class)
            ->addArgument([$voterDef1$voterDef2]);
        $container->setParameter('kernel.debug', true);

        $compilerPass = new AddSecurityVotersPass();
        
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Reference;

/** * Configures a token handler for decoding and validating an OIDC token. */
class OidcTokenHandlerFactory implements TokenHandlerFactoryInterface
{
    public function create(ContainerBuilder $container, string $id, array|string $config): void
    {
        $tokenHandlerDefinition = $container->setDefinition($id(new ChildDefinition('security.access_token_handler.oidc'))
            ->replaceArgument(2, $config['audience'])
            ->replaceArgument(3, $config['issuers'])
            ->replaceArgument(4, $config['claim'])
        );

        if (!ContainerBuilder::willBeAvailable('web-token/jwt-core', Algorithm::class['symfony/security-bundle'])) {
            throw new LogicException('You cannot use the "oidc" token handler since "web-token/jwt-core" is not installed. Try running "composer require web-token/jwt-core".');
        }

        // @see Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SignatureAlgorithmFactory         // for supported algorithms
public function __construct(RouterInterface $router, FileLinkFormatter $fileLinkFormatter = null)
    {
        parent::__construct();

        $this->router = $router;
        $this->fileLinkFormatter = $fileLinkFormatter;
    }

    protected function configure(): void
    {
        $this
            ->setDefinition([
                new InputArgument('name', InputArgument::OPTIONAL, 'A route name'),
                new InputOption('show-controllers', null, InputOption::VALUE_NONE, 'Show assigned controllers in overview'),
                new InputOption('format', null, InputOption::VALUE_REQUIRED, sprintf('The output format ("%s")', implode('", "', $this->getAvailableFormatOptions())), 'txt'),
                new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw route(s)'),
            ])
            ->setHelp(<<<'EOF' The <info>%command.name%</info> displays the configured routes: <info>php %command.full_name%</info> EOF
            )

class X509Factory implements AuthenticatorFactoryInterface
{
    public const PRIORITY = -10;

    public function createAuthenticator(ContainerBuilder $container, string $firewallName, array $config, string $userProviderId): string
    {
        $authenticatorId = 'security.authenticator.x509.'.$firewallName;
        $container
            ->setDefinition($authenticatorIdnew ChildDefinition('security.authenticator.x509'))
            ->replaceArgument(0, new Reference($userProviderId))
            ->replaceArgument(2, $firewallName)
            ->replaceArgument(3, $config['user'])
            ->replaceArgument(4, $config['credentials'])
            ->replaceArgument(6, $config['user_identifier'])
        ;

        return $authenticatorId;
    }

    public function getPriority(): int
    {
if (!class_exists($type) && !interface_exists($type, false)) {
                                $definition->setClass('object');
                            }
                            foreach ($lazy as $v) {
                                $definition->addTag('proxy', ['interface' => $v]);
                            }
                        }

                        if ($definition->getClass() !== (string) $value || $definition->getTag('proxy')) {
                            $value .= '.'.$this->container->hash([$definition->getClass()$definition->getTag('proxy')]);
                        }
                        $this->container->setDefinition($value = '.lazy.'.$value$definition);
                        $value = new Reference($value);
                    }
                    $arguments[$index] = $value;

                    continue 2;
                }

                foreach ($parameter->getAttributes(AutowireDecorated::class) as $attribute) {
                    $arguments[$index] = $this->processValue($attribute->newInstance());

                    continue 2;
                }
if (str_starts_with($class, '\\')) {
                $class = substr($class, 1);
            }

            try {
                $class = $this->container->getParameterBag()->resolveValue($class);
            } catch (ParameterNotFoundException) {
            }

            $nodes[$id] = ['class' => str_replace('\\', '\\\\', $class), 'attributes' => array_merge($this->options['node.definition']['style' => $definition->isShared() ? 'filled' : 'dotted'])];
            $container->setDefinition($idnew Definition('stdClass'));
        }

        foreach ($container->getServiceIds() as $id) {
            if (\array_key_exists($id$container->getAliases())) {
                continue;
            }

            if (!$container->hasDefinition($id)) {
                $nodes[$id] = ['class' => str_replace('\\', '\\\\', $container->get($id)::class), 'attributes' => $this->options['node.instance']];
            }
        }

        

class ElasticsearchProfileCompilerPassTest extends TestCase
{
    public function testCompilerPassRemovesDataCollector(): void
    {
        $container = new ContainerBuilder();

        $def = new Definition(DataCollector::class);
        $def->setPublic(true);

        $container->setDefinition(DataCollector::class$def);

        $container->setParameter('kernel.debug', false);

        $compilerPass = new ElasticsearchProfileCompilerPass();
        $compilerPass->process($container);

        static::assertFalse($container->hasDefinition(DataCollector::class));
    }

    public function testCompilerPassDecoratesClient(): void
    {
        
private Command $command;

    /** * @return void */
    protected function configure()
    {
        $this->ignoreValidationErrors();

        $this
            ->setName('help')
            ->setDefinition([
                new InputArgument('command_name', InputArgument::OPTIONAL, 'The command name', 'help', fn () => array_keys((new ApplicationDescription($this->getApplication()))->getCommands())),
                new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (txt, xml, json, or md)', 'txt', fn () => (new DescriptorHelper())->getFormats()),
                new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw command help'),
            ])
            ->setDescription('Display help for a command')
            ->setHelp(<<<'EOF' The <info>%command.name%</info> command displays help for a given command: <info>%command.full_name% list</info> You can also output the help in other formats by using the <comment>--format</comment> option: <info>%command.full_name% --format=xml list</info> To display the list of available commands, please use the <info>list</info> command.
public function __construct(UuidFactory $factory = null)
    {
        $this->factory = $factory ?? new UuidFactory();

        parent::__construct();
    }

    protected function configure(): void
    {
        $this
            ->setDefinition([
                new InputOption('time-based', null, InputOption::VALUE_REQUIRED, 'The timestamp, to generate a time-based UUID: a parsable date/time string'),
                new InputOption('node', null, InputOption::VALUE_REQUIRED, 'The UUID whose node part should be used as the node of the generated UUID'),
                new InputOption('name-based', null, InputOption::VALUE_REQUIRED, 'The name, to generate a name-based UUID'),
                new InputOption('namespace', null, InputOption::VALUE_REQUIRED, 'The UUID to use at the namespace for named-based UUIDs, predefined namespaces keywords "dns", "url", "oid" and "x500" are accepted'),
                new InputOption('random-based', null, InputOption::VALUE_NONE, 'To generate a random-based UUID'),
                new InputOption('count', 'c', InputOption::VALUE_REQUIRED, 'The number of UUID to generate', 1),
                new InputOption('format', 'f', InputOption::VALUE_REQUIRED, sprintf('The UUID output format ("%s")', implode('", "', $this->getAvailableFormatOptions())), 'rfc4122'),
            ])
            ->setHelp(<<<'EOF' The <info>%command.name%</info> generates a UUID. <info>php %command.full_name%</info> To generate a time-based UUID: <info>php %command.full_name% --time-based=now</info> To specify a time-based UUID's node: <info>php %command.full_name% --time-based=@1613480254 --node=fb3502dc-137e-4849-8886-ac90d07f64a7</info> To generate a name-based UUID: <info>php %command.full_name% --name-based=foo</info> To specify a name-based UUID's namespace: <info>php %command.full_name% --name-based=bar --namespace=fb3502dc-137e-4849-8886-ac90d07f64a7</info> To generate a random-based UUID: <info>php %command.full_name% --random-based</info> To generate several UUIDs: <info>php %command.full_name% --count=10</info> To output a specific format: <info>php %command.full_name% --format=base58</info>
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\Compiler\ResolveChildDefinitionsPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;

class ResolveChildDefinitionsPassTest extends TestCase
{
    public function testProcess()
    {
        $container = new ContainerBuilder();
        $container->register('parent', 'foo')->setArguments(['moo', 'b'])->setProperty('foo', 'moo');
        $container->setDefinition('child', new ChildDefinition('parent'))
            ->replaceArgument(0, 'a')
            ->setProperty('foo', 'bar')
            ->setClass('bar')
        ;

        $this->process($container);

        $def = $container->getDefinition('child');
        $this->assertNotInstanceOf(ChildDefinition::class$def);
        $this->assertEquals('bar', $def->getClass());
        $this->assertEquals(['a', 'b']$def->getArguments());
        
Home | Imprint | This part of the site doesn't use cookies.