Reference example


class ResolveServiceSubscribersPass extends AbstractRecursivePass
{
    protected bool $skipScalars = true;

    private ?string $serviceLocator = null;

    protected function processValue(mixed $value, bool $isRoot = false): mixed
    {
        if ($value instanceof Reference && $this->serviceLocator && \in_array((string) $value[ContainerInterface::class, ServiceProviderInterface::class], true)) {
            return new Reference($this->serviceLocator);
        }

        if (!$value instanceof Definition) {
            return parent::processValue($value$isRoot);
        }

        $serviceLocator = $this->serviceLocator;
        $this->serviceLocator = null;

        if ($value->hasTag('container.service_subscriber.locator')) {
            $this->serviceLocator = $value->getTag('container.service_subscriber.locator')[0]['id'];
            
throw new LogicException('No twig loaders found. You need to tag at least one loader with "twig.loader".');
        }

        if (1 === $found) {
            $container->setAlias('twig.loader', $id);
        } else {
            $chainLoader = $container->getDefinition('twig.loader.chain');
            krsort($prioritizedLoaders);

            foreach ($prioritizedLoaders as $loaders) {
                foreach ($loaders as $loader) {
                    $chainLoader->addMethodCall('addLoader', [new Reference($loader)]);
                }
            }

            $container->setAlias('twig.loader', 'twig.loader.chain');
        }
    }
}

    public function process(ContainerBuilder $container)
    {
        if (false === $container->hasDefinition('routing.resolver')) {
            return;
        }

        $definition = $container->getDefinition('routing.resolver');

        foreach ($this->findAndSortTaggedServices('routing.loader', $container) as $id) {
            $definition->addMethodCall('addLoader', [new Reference($id)]);
        }
    }
}
if (isset($tags[0]['clearer'])) {
                $clearer = $tags[0]['clearer'];
                while ($container->hasAlias($clearer)) {
                    $clearer = (string) $container->getAlias($clearer);
                }
            } else {
                $clearer = null;
            }
            unset($tags[0]['clearer']$tags[0]['name']);

            if (isset($tags[0]['provider'])) {
                $tags[0]['provider'] = new Reference(static::getServiceProvider($container$tags[0]['provider']));
            }

            if (ChainAdapter::class === $class) {
                $adapters = [];
                foreach ($adapter->getArgument(0) as $provider => $adapter) {
                    if ($adapter instanceof ChildDefinition) {
                        $chainedPool = $adapter;
                    } else {
                        $chainedPool = $adapter = new ChildDefinition($adapter);
                    }

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

        $this->assertSame(['Baz\Qux', 'getInstance']$factory->getFactory()[0]->getFactory());
    }

    public static function provideFulfilledFactories()
    {
        return [
            [['Foo\Bar', 'create']],
            [[new Reference('foo'), 'create']],
            [[new Definition('Baz'), 'create']],
        ];
    }

    /** * @dataProvider provideFulfilledFactories */
    public function testIgnoresFulfilledFactories($factory)
    {
        $container = new ContainerBuilder();
        $definition = new Definition();
        
if ('dark' !== $config['theme']) {
            $container->getDefinition('var_dumper.html_dumper')
                ->addMethodCall('setTheme', [$config['theme']]);
        }

        if (null === $config['dump_destination']) {
            $container->getDefinition('var_dumper.command.server_dump')
                ->setClass(ServerDumpPlaceholderCommand::class)
            ;
        } elseif (str_starts_with($config['dump_destination'], 'tcp://')) {
            $container->getDefinition('debug.dump_listener')
                ->replaceArgument(2, new Reference('var_dumper.server_connection'))
            ;
            $container->getDefinition('data_collector.dump')
                ->replaceArgument(4, new Reference('var_dumper.server_connection'))
            ;
            $container->getDefinition('var_dumper.dump_server')
                ->replaceArgument(0, $config['dump_destination'])
            ;
            $container->getDefinition('var_dumper.server_connection')
                ->replaceArgument(0, $config['dump_destination'])
            ;
        } else {
            

class CacheCollectorTest extends KernelTestBase {

  /** * {@inheritdoc} */
  public function register(ContainerBuilder $container) {
    parent::register($container);
    // Change container to database cache backends.     $container
      ->register('cache_factory', 'Drupal\Core\Cache\CacheFactory')
      ->addArgument(new Reference('settings'))
      ->addMethodCall('setContainer', [new Reference('service_container')]);

    // Change container to use database lock backends.     $container
      ->register('lock', 'Drupal\Core\Lock\DatabaseLockBackend')
      ->addArgument(new Reference('database'));
  }

  /** * Tests setting and invalidating. * * @dataProvider providerTestInvalidCharacters */

class ResolveServiceSubscribersPass extends AbstractRecursivePass
{
    private ?string $serviceLocator = null;

    protected function processValue(mixed $value, bool $isRoot = false): mixed
    {
        if ($value instanceof Reference && $this->serviceLocator && \in_array((string) $value[ContainerInterface::class, ServiceProviderInterface::class], true)) {
            return new Reference($this->serviceLocator);
        }

        if (!$value instanceof Definition) {
            return parent::processValue($value$isRoot);
        }

        $serviceLocator = $this->serviceLocator;
        $this->serviceLocator = null;

        if ($value->hasTag('container.service_subscriber.locator')) {
            $this->serviceLocator = $value->getTag('container.service_subscriber.locator')[0]['id'];
            
public function testArrayCallable()
    {
        $attribute = new AutowireCallable(callable: ['My\StaticClass', 'my_callable']);

        self::assertSame(['My\StaticClass', 'my_callable']$attribute->value);
        self::assertFalse($attribute->lazy);
    }

    public function testArrayCallableWithReferenceAndMethod()
    {
        $attribute = new AutowireCallable(callable: [new Reference('my_service'), 'my_callable']);

        self::assertEquals([new Reference('my_service'), 'my_callable']$attribute->value);
        self::assertFalse($attribute->lazy);
    }

    public function testArrayCallableWithReferenceOnly()
    {
        $attribute = new AutowireCallable(callable: [new Reference('my_service')]);

        self::assertEquals([new Reference('my_service')]$attribute->value);
        self::assertFalse($attribute->lazy);
    }

        return parent::getKey().'-ldap';
    }

    public function createAuthenticator(ContainerBuilder $container, string $firewallName, array $config, string $userProviderId): string
    {
        $key = str_replace('-', '_', $this->getKey());
        $authenticatorId = parent::createAuthenticator($container$firewallName$config$userProviderId);

        $container->setDefinition('security.listener.'.$key.'.'.$firewallNamenew Definition(CheckLdapCredentialsListener::class))
            ->addTag('kernel.event_subscriber', ['dispatcher' => 'security.event_dispatcher.'.$firewallName])
            ->addArgument(new Reference('security.ldap_locator'))
        ;

        $ldapAuthenticatorId = 'security.authenticator.'.$key.'.'.$firewallName;
        $definition = $container->setDefinition($ldapAuthenticatorIdnew Definition(LdapAuthenticator::class))
            ->setArguments([
                new Reference($authenticatorId),
                $config['service'],
                $config['dn_string'],
                $config['search_dn'],
                $config['search_password'],
            ]);

        
throw new InvalidArgumentException(sprintf('The service "%s" tagged "%s" must be a subclass of "%s".', $id, 'console.command', Command::class));
                }
                $description = str_replace('%', '%%', $class::getDefaultDescription() ?? '');
            }

            if ($description) {
                $definition->addMethodCall('setDescription', [$description]);

                $container->register('.'.$id.'.lazy', LazyCommand::class)
                    ->setArguments([$commandName$aliases$description$isHiddennew ServiceClosureArgument($lazyCommandRefs[$id])]);

                $lazyCommandRefs[$id] = new Reference('.'.$id.'.lazy');
            }
        }

        $container
            ->register('console.command_loader', ContainerCommandLoader::class)
            ->setPublic(true)
            ->addTag('container.no_preload')
            ->setArguments([ServiceLocatorTagPass::register($container$lazyCommandRefs)$lazyCommandMap]);

        $container->setParameter('console.command.ids', $serviceIds);
    }
}
$this->assertSame($def$container->getDefinition('foo_service_id')->getArgument(0));
    }

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

        $container->register('nested_error', 'stdClass')
            ->addError('Things went wrong!');

        $container->register('bar', 'stdClass')
            ->addArgument(new Reference('nested_error'));

        $container->register('foo', 'stdClass')
            ->addArgument(new Reference('bar', ContainerBuilder::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE));

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

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('Things went wrong!');
        $container->get('foo');
    }

    
if ($isRef = !$valueIsStatic = $values[$k] !== $objectsPool) {
                $values[$k] = &$value; // Break hard references to make $values completely                 unset($value);         // independent from the original structure                 $refs[$k] = $value = $values[$k];
                if ($value instanceof Reference && 0 > $value->id) {
                    $valuesAreStatic = false;
                    ++$value->count;
                    continue;
                }
                $refsPool[] = [&$refs[$k]$value, &$value];
                $refs[$k] = $values[$k] = new Reference(-\count($refsPool)$value);
            }

            if (\is_array($value)) {
                if ($value) {
                    $value = self::prepare($value$objectsPool$refsPool$objectsCount$valueIsStatic);
                }
                goto handle_value;
            } elseif (!\is_object($value) || $value instanceof \UnitEnum) {
                goto handle_value;
            }

            

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

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

        return $authenticatorId;
    }

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

    
$definition = new Definition(\stdClass::class);
        $definition->addTag('security.expression_language_provider');
        $container->setDefinition('some_security_provider', $definition->setPublic(true));

        $container->register('security.expression_language', \stdClass::class)->setPublic(true);
        $container->compile();

        $calls = $container->getDefinition('security.expression_language')->getMethodCalls();
        $this->assertCount(1, $calls);
        $this->assertEquals('registerProvider', $calls[0][0]);
        $this->assertEquals(new Reference('some_security_provider')$calls[0][1][0]);
    }

    public function testProcessForSecurityAlias()
    {
        $container = new ContainerBuilder();
        $container->addCompilerPass(new AddExpressionLanguageProvidersPass());

        $definition = new Definition(\stdClass::class);
        $definition->addTag('security.expression_language_provider');
        $container->setDefinition('some_security_provider', $definition->setPublic(true));

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