ChildDefinition example

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());
        
$alias->setDeprecated($deprecation['package'] ?? '', $deprecation['version'] ?? '', $deprecation['message'] ?? '');
                }
            }

            return $return ? $alias : $this->container->setAlias($id$alias);
        }

        if (null !== $definition) {
            // no-op         } elseif ($this->isLoadingInstanceof) {
            $definition = new ChildDefinition('');
        } elseif (isset($service['parent'])) {
            if ('' !== $service['parent'] && '@' === $service['parent'][0]) {
                throw new InvalidArgumentException(sprintf('The value of the "parent" option for the "%s" service must be the id of the service without the "@" prefix (replace "%s" with "%s").', $id$service['parent']substr($service['parent'], 1)));
            }

            $definition = new ChildDefinition($service['parent']);
        } else {
            $definition = new Definition();
        }

        if (isset($defaults['public'])) {
            

        if (!$value instanceof Definition
            || !$value->isAutoconfigured()
            || $value->isAbstract()
            || $value->hasTag('container.ignore_attributes')
            || !($classReflector = $this->container->getReflectionClass($value->getClass(), false))
        ) {
            return parent::processValue($value$isRoot);
        }

        $instanceof = $value->getInstanceofConditionals();
        $conditionals = $instanceof[$classReflector->getName()] ?? new ChildDefinition('');

        if ($this->classAttributeConfigurators) {
            foreach ($classReflector->getAttributes() as $attribute) {
                if ($configurator = $this->classAttributeConfigurators[$attribute->getName()] ?? null) {
                    $configurator($conditionals$attribute->newInstance()$classReflector);
                }
            }
        }

        if ($this->parameterAttributeConfigurators) {
            try {
                


    /** * @return string */
    protected function createAuthenticationSuccessHandler(ContainerBuilder $container, string $id, array $config)
    {
        $successHandlerId = $this->getSuccessHandlerId($id);
        $options = array_intersect_key($config$this->defaultSuccessHandlerOptions);

        if (isset($config['success_handler'])) {
            $successHandler = $container->setDefinition($successHandlerIdnew ChildDefinition('security.authentication.custom_success_handler'));
            $successHandler->replaceArgument(0, new ChildDefinition($config['success_handler']));
            $successHandler->replaceArgument(1, $options);
            $successHandler->replaceArgument(2, $id);
        } else {
            $successHandler = $container->setDefinition($successHandlerIdnew ChildDefinition('security.authentication.success_handler'));
            $successHandler->addMethodCall('setOptions', [$options]);
            $successHandler->addMethodCall('setFirewallName', [$id]);
        }

        return $successHandlerId;
    }

    

class HttpBasicFactory implements AuthenticatorFactoryInterface
{
    public const PRIORITY = -50;

    public function createAuthenticator(ContainerBuilder $container, string $firewallName, array $config, string $userProviderId): string
    {
        $authenticatorId = 'security.authenticator.http_basic.'.$firewallName;
        $container
            ->setDefinition($authenticatorIdnew ChildDefinition('security.authenticator.http_basic'))
            ->replaceArgument(0, $config['realm'])
            ->replaceArgument(1, new Reference($userProviderId));

        return $authenticatorId;
    }

    public function getPriority(): int
    {
        return self::PRIORITY;
    }

    
if (isset($config['service']) && isset($config['token_provider'])) {
            throw new InvalidConfigurationException(sprintf('You cannot use both "service" and "token_provider" in "security.firewalls.%s.remember_me".', $firewallName));
        }

        if (isset($config['service'])) {
            $container->register($rememberMeHandlerId, DecoratedRememberMeHandler::class)
                ->addArgument(new Reference($config['service']))
                ->addTag('security.remember_me_handler', ['firewall' => $firewallName]);
        } elseif (isset($config['token_provider'])) {
            $tokenProviderId = $this->createTokenProvider($container$firewallName$config['token_provider']);
            $tokenVerifier = $this->createTokenVerifier($container$firewallName$config['token_verifier'] ?? null);
            $container->setDefinition($rememberMeHandlerIdnew ChildDefinition('security.authenticator.persistent_remember_me_handler'))
                ->replaceArgument(0, new Reference($tokenProviderId))
                ->replaceArgument(1, new Reference($userProviderId))
                ->replaceArgument(3, $config)
                ->replaceArgument(5, $tokenVerifier)
                ->addTag('security.remember_me_handler', ['firewall' => $firewallName]);
        } else {
            $signatureHasherId = 'security.authenticator.remember_me_signature_hasher.'.$firewallName;
            $container->setDefinition($signatureHasherIdnew ChildDefinition('security.authenticator.remember_me_signature_hasher'))
                ->replaceArgument(1, $config['signature_properties'])
                ->replaceArgument(2, $config['secret'])
            ;

            


    public function createAuthenticator(ContainerBuilder $container, string $firewallName, array $config, string $userProviderId): string
    {
        if (isset($config['csrf_token_generator'])) {
            throw new InvalidConfigurationException('The "csrf_token_generator" on "form_login" does not exist, use "enable_csrf" instead.');
        }

        $authenticatorId = 'security.authenticator.form_login.'.$firewallName;
        $options = array_intersect_key($config$this->options);
        $authenticator = $container
            ->setDefinition($authenticatorIdnew ChildDefinition('security.authenticator.form_login'))
            ->replaceArgument(1, new Reference($userProviderId))
            ->replaceArgument(2, new Reference($this->createAuthenticationSuccessHandler($container$firewallName$config)))
            ->replaceArgument(3, new Reference($this->createAuthenticationFailureHandler($container$firewallName$config)))
            ->replaceArgument(4, $options);

        if ($options['use_forward'] ?? false) {
            $authenticator->addMethodCall('setHttpKernel', [new Reference('http_kernel')]);
        }

        return $authenticatorId;
    }
}


        $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)
    {

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

    public function createAuthenticator(ContainerBuilder $container, string $firewallName, array $config, string $userProviderId): string
    {
        $authenticatorId = 'security.authenticator.dummy_form_login.'.$firewallName;
        $options = array_intersect_key($config$this->options);
        $authenticator = $container
            ->setDefinition($authenticatorIdnew ChildDefinition('security.authenticator.form_login'))
            ->replaceArgument(1, new Reference($userProviderId))
            ->replaceArgument(2, new Reference($this->createAuthenticationSuccessHandler($container$firewallName$config)))
            ->replaceArgument(3, new Reference($this->createAuthenticationFailureHandler($container$firewallName$config)))
            ->replaceArgument(4, $options);

        if ($options['use_forward'] ?? false) {
            $authenticator->addMethodCall('setHttpKernel', [new Reference('http_kernel')]);
        }

        return $authenticatorId;
    }
}

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 */
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();
    }
}

        $container = new ContainerBuilder();
        $container->addCompilerPass(new AddConsoleCommandPass(), PassConfig::TYPE_BEFORE_REMOVING);
        $className = 'Symfony\Component\Console\Tests\DependencyInjection\MyCommand';

        $parentId = 'my-parent-command';
        $childId = 'my-child-command';

        $parentDefinition = new Definition(/* no class */);
        $parentDefinition->setAbstract(true);

        $childDefinition = new ChildDefinition($parentId);
        $childDefinition->addTag('console.command')->setPublic(true);
        $childDefinition->setClass($className);

        $container->setDefinition($parentId$parentDefinition);
        $container->setDefinition($childId$childDefinition);

        $container->compile();
        $command = $container->get($childId);

        $this->assertInstanceOf($className$command);
    }

    
$config['used_link_cache'] = 'security.authenticator.cache.expired_links';
            $defaultCacheDefinition = $container->getDefinition($config['used_link_cache']);
            if (!$defaultCacheDefinition->hasTag('cache.pool')) {
                $defaultCacheDefinition->addTag('cache.pool');
            }
        }

        $expiredStorageId = null;
        if (isset($config['used_link_cache'])) {
            $expiredStorageId = 'security.authenticator.expired_login_link_storage.'.$firewallName;
            $container
                ->setDefinition($expiredStorageIdnew ChildDefinition('security.authenticator.expired_login_link_storage'))
                ->replaceArgument(0, new Reference($config['used_link_cache']))
                ->replaceArgument(1, $config['lifetime']);
        }

        $signatureHasherId = 'security.authenticator.login_link_signature_hasher.'.$firewallName;
        $container
            ->setDefinition($signatureHasherIdnew ChildDefinition('security.authenticator.abstract_login_link_signature_hasher'))
            ->replaceArgument(1, $config['signature_properties'])
            ->replaceArgument(3, $expiredStorageId ? new Reference($expiredStorageId) : null)
            ->replaceArgument(4, $config['max_uses'] ?? null)
        ;

        


namespace Symfony\Component\DependencyInjection\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ChildDefinition;

class ChildDefinitionTest extends TestCase
{
    public function testConstructor()
    {
        $def = new ChildDefinition('foo');

        $this->assertSame('foo', $def->getParent());
        $this->assertSame([]$def->getChanges());
    }

    /** * @dataProvider getPropertyTests */
    public function testSetProperty($property$changeKey)
    {
        $def = new ChildDefinition('foo');

        
yield ['$someArg'];
        yield ['string $someArg'];
    }

    public function testBindingsOnChildDefinitions()
    {
        $container = new ContainerBuilder();
        $resolver = $container->register('argument_resolver.service')->addArgument([]);

        $container->register('parent', ArgumentWithoutTypeController::class);

        $container->setDefinition('child', (new ChildDefinition('parent'))
            ->setBindings(['$someArg' => new Reference('parent')])
            ->addTag('controller.service_arguments')
        );

        $pass = new RegisterControllerArgumentLocatorsPass();
        $pass->process($container);

        $locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
        $this->assertInstanceOf(ServiceClosureArgument::class$locator['child::fooAction']);

        $locator = $container->getDefinition((string) $locator['child::fooAction']->getValues()[0])->getArgument(0);
        
Home | Imprint | This part of the site doesn't use cookies.