ServiceClosureArgument example


        $this->assertStringMatchesFormatFile(self::$fixturesPath.'/php/services9_as_files.txt', $dump);
    }

    public function testDumpAsFilesWithTypedReference()
    {
        $container = include self::$fixturesPath.'/containers/container10.php';
        $container->getDefinition('foo')->addTag('hot');
        $container->register('bar', 'stdClass');
        $container->register('closure', 'stdClass')
            ->setProperty('closures', [
                new ServiceClosureArgument(new TypedReference('foo', \stdClass::class$container::IGNORE_ON_UNINITIALIZED_REFERENCE)),
            ])
            ->setPublic(true);
        $container->compile();
        $dumper = new PhpDumper($container);
        $dump = print_r($dumper->dump(['as_files' => true, 'file' => __DIR__, 'hot_path_tag' => 'hot', 'inline_factories' => false, 'inline_class_loader' => false]), true);
        if ('\\' === \DIRECTORY_SEPARATOR) {
            $dump = str_replace("'.\\DIRECTORY_SEPARATOR.'", '/', $dump);
        }

        $this->assertStringMatchesFormatFile(self::$fixturesPath.'/php/services10_as_files.txt', $dump);
    }

    
new RegisterServiceSubscribersPass())->process($container);
        (new ResolveServiceSubscribersPass())->process($container);

        $foo = $container->getDefinition('foo');
        $locator = $container->getDefinition((string) $foo->getArgument(0));

        $this->assertFalse($locator->isPublic());
        $this->assertSame(ServiceLocator::class$locator->getClass());

        $expected = [
            TestServiceSubscriber::class => new ServiceClosureArgument(new TypedReference(TestServiceSubscriber::class, TestServiceSubscriber::class)),
            CustomDefinition::class => new ServiceClosureArgument(new TypedReference(CustomDefinition::class, CustomDefinition::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE)),
            'bar' => new ServiceClosureArgument(new TypedReference(CustomDefinition::class, CustomDefinition::class, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, 'bar')),
            'baz' => new ServiceClosureArgument(new TypedReference(CustomDefinition::class, CustomDefinition::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE, 'baz')),
            'late_alias' => new ServiceClosureArgument(new TypedReference(TestDefinition1::class, TestDefinition1::class, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, 'late_alias')),
        ];

        $this->assertEquals($expected$container->getDefinition((string) $locator->getFactory()[0])->getArgument(0));
    }

    public function testWithAttributes()
    {
        
$container
                ->getDefinition('annotations.filesystem_cache_adapter')
                ->replaceArgument(2, $cacheDir)
            ;
        }

        $container
            ->getDefinition('annotations.cached_reader')
            ->replaceArgument(2, $config['debug'])
            // reference the cache provider without using it until AddAnnotationsCachedReaderPass runs             ->addArgument(new ServiceClosureArgument(new Reference($cacheService)))
        ;

        $container->setAlias('annotation_reader', 'annotations.cached_reader');
        $container->setAlias(Reader::classnew Alias('annotations.cached_reader', false));
        $container->removeDefinition('annotations.psr_cached_reader');
    }

    private function registerPropertyAccessConfiguration(array $config, ContainerBuilder $container, PhpFileLoader $loader): void
    {
        if (!$this->readConfigEnabled('property_access', $container$config)) {
            return;
        }
$inlinedServiceArguments = $container->getDefinition('locator_dependent_inline_service')->getArguments();
        $this->assertEquals((new Definition(\stdClass::class))->setPublic(false)$container->getDefinition((string) $inlinedServiceArguments[0]->getValues()['foo']));
        $this->assertEquals((new Definition(\stdClass::class))->setPublic(false)$container->getDefinition((string) $inlinedServiceArguments[0]->getValues()['bar']));
    }

    public function testParseServiceClosure()
    {
        $container = new ContainerBuilder();
        $loader = new XmlFileLoader($containernew FileLocator(self::$fixturesPath.'/xml'));
        $loader->load('services_with_service_closure.xml');

        $this->assertEquals(new ServiceClosureArgument(new Reference('bar', ContainerInterface::IGNORE_ON_INVALID_REFERENCE))$container->getDefinition('foo')->getArgument(0));
    }

    public function testParseServiceTagsWithArrayAttributes()
    {
        $container = new ContainerBuilder();
        $loader = new XmlFileLoader($containernew FileLocator(self::$fixturesPath.'/xml'));
        $loader->load('services_with_array_tags.xml');

        $this->assertEquals(['foo_tag' => [['foo' => 'bar', 'bar' => ['foo' => 'bar', 'bar' => 'foo']]]]$container->getDefinition('foo')->getTags());
    }

    

class RegisterLdapLocatorPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container): void
    {
        $definition = $container->setDefinition('security.ldap_locator', new Definition(ServiceLocator::class));

        $locators = [];
        foreach ($container->findTaggedServiceIds('ldap') as $serviceId => $tags) {
            $locators[$serviceId] = new ServiceClosureArgument(new Reference($serviceId));
        }

        $definition->addArgument($locators);
    }
}

        $container->register(ServiceProperties::class, ServiceProperties::class)
            ->setProperties([new Reference('translator')])
        ;
        $container->register(ServiceMethodCalls::class, ServiceMethodCalls::class)
            ->setMethodCalls([['setTranslator', [new Reference('translator')]]])
        ;
        $container->register('service_rc')
            ->setArguments([new Definition()new Reference(ServiceMethodCalls::class)])
        ;
        $serviceLocator1 = $container->register('.service_locator.foo', ServiceLocator::class)
            ->setArguments([new ServiceClosureArgument(new Reference('translator'))])
        ;
        $serviceLocator2 = (new Definition(ServiceLocator::class))
            ->setArguments([ServiceSubscriber::classnew Reference('service_container')])
            ->setFactory([$serviceLocator1, 'withContext'])
        ;
        $container->register('service_subscriber', ServiceSubscriber::class)
            ->setArguments([$serviceLocator2])
        ;
        $container->register('.service_locator.bar', ServiceLocator::class)
            ->setArguments([[
                ControllerArguments::class.'::index' => new ServiceClosureArgument(new Reference('.service_locator.foo')),
                
 else {
                unset($privateServices[$id]);
            }
        }

        foreach ($container->getAliases() as $id => $target) {
            while ($container->hasAlias($target = (string) $target)) {
                $target = $container->getAlias($target);
            }

            if ($definitions[$target]->hasTag('container.private')) {
                $privateServices[$id] = new ServiceClosureArgument(new Reference($target));
            }

            $renamedIds[$id] = $target;
        }

        $privateContainer->replaceArgument(0, $privateServices);

        if ($container->hasDefinition('test.service_container') && $renamedIds) {
            $container->getDefinition('test.service_container')->setArgument(2, $renamedIds);
        }
    }
}
->addMethodCall('addLoader', ['xlf', new Reference('translation.xliff_loader')])
        ;
        $this->assertEquals($expectedReader$reader);

        $expectedLoader = (new Definition())
            ->addTag('translation.loader', ['alias' => 'xliff', 'legacy-alias' => 'xlf'])
        ;
        $this->assertEquals($expectedLoader$loader);

        $this->assertSame(['translation.xliff_loader' => ['xliff', 'xlf']]$translator->getArgument(3));

        $expected = ['translation.xliff_loader' => new ServiceClosureArgument(new Reference('translation.xliff_loader'))];
        $this->assertEquals($expected$container->getDefinition((string) $translator->getArgument(0))->getArgument(0));
    }

    public function testValidCommandsViewPathsArgument()
    {
        $container = new ContainerBuilder();
        $container->register('translator.default')
            ->setArguments([null, null, null, null])
        ;
        $debugCommand = $container->register('console.command.translation_debug')
            ->setArguments([null, null, null, null, null, [][]])
        ;
->setDecoratedService('Test\soon_private_service_decorated')
            ->setArguments(['Test\soon_private_service_decorator.inner']);

        $container->register('Test\private_used_shared_service');
        $container->register('Test\private_unused_shared_service');
        $container->register('Test\private_used_non_shared_service')->setShared(false);
        $container->register('Test\private_unused_non_shared_service')->setShared(false);

        $container->compile();

        $expected = [
            'Test\private_used_shared_service' => new ServiceClosureArgument(new Reference('Test\private_used_shared_service')),
            'Test\private_used_non_shared_service' => new ServiceClosureArgument(new Reference('Test\private_used_non_shared_service')),
            'Test\soon_private_service' => new ServiceClosureArgument(new Reference('.container.private.Test\soon_private_service')),
            'Test\soon_private_service_decorator' => new ServiceClosureArgument(new Reference('.container.private.Test\soon_private_service_decorated')),
            'Test\soon_private_service_decorated' => new ServiceClosureArgument(new Reference('.container.private.Test\soon_private_service_decorated')),
        ];

        $privateServices = $container->getDefinition('test.private_services_locator')->getArgument(0);
        unset($privateServices[\Symfony\Component\DependencyInjection\ContainerInterface::class]$privateServices[ContainerInterface::class]);

        $this->assertEquals($expected$privateServices);
        $this->assertFalse($container->getDefinition('Test\private_used_non_shared_service')->isShared());
    }
if ($this->beforeRemoving) {
            // prevent inlining of the reverse container             $services['reverse_container'] = new Reference('reverse_container', $refType);
        }
        $locator = $container->getDefinition('reverse_container')->getArgument(1);

        if ($locator instanceof Reference) {
            $locator = $container->getDefinition((string) $locator);
        }
        if ($locator instanceof Definition) {
            foreach ($services as $id => $ref) {
                $services[$id] = new ServiceClosureArgument($ref);
            }
            $locator->replaceArgument(0, $services);
        } else {
            $locator->setValues($services);
        }
    }
}
if ($this->beforeRemoving) {
            // prevent inlining of the reverse container             $services['reverse_container'] = new Reference('reverse_container', $refType);
        }
        $locator = $container->getDefinition('reverse_container')->getArgument(1);

        if ($locator instanceof Reference) {
            $locator = $container->getDefinition((string) $locator);
        }
        if ($locator instanceof Definition) {
            foreach ($services as $id => $ref) {
                $services[$id] = new ServiceClosureArgument($ref);
            }
            $locator->replaceArgument(0, $services);
        } else {
            $locator->setValues($services);
        }
    }
}
$arg = $this->getArgumentsAsPhp($arg$name$file);
                    $arguments[$key] = new IteratorArgument($arg);
                    break;
                case 'closure':
                case 'service_closure':
                    if ('' !== $arg->getAttribute('id')) {
                        $arg = new Reference($arg->getAttribute('id')$invalidBehavior);
                    } else {
                        $arg = $this->getArgumentsAsPhp($arg$name$file);
                    }
                    $arguments[$key] = match ($type) {
                        'service_closure' => new ServiceClosureArgument($arg),
                        'closure' => (new Definition('Closure'))
                            ->setFactory(['Closure', 'fromCallable'])
                            ->addArgument($arg),
                    };
                    break;
                case 'service_locator':
                    $arg = $this->getArgumentsAsPhp($arg$name$file);

                    if (isset($arg[0])) {
                        trigger_deprecation('symfony/dependency-injection', '6.3', 'Skipping "key" argument or using integers as values in a "service_locator" tag is deprecated. The keys will default to the IDs of the original services in 7.0.');
                    }

                    
if ($i === $k) {
                if ($v instanceof Reference) {
                    unset($services[$k]);
                    $k = (string) $v;
                }
                ++$i;
            } elseif (\is_int($k)) {
                $i = null;
            }

            $services[$k] = new ServiceClosureArgument($v);
        }
        ksort($services);

        $value->setArgument(0, $services);

        $id = '.service_locator.'.ContainerBuilder::hash($value);

        if ($isRoot) {
            if ($id !== $this->currentId) {
                $this->container->setAlias($idnew Alias($this->currentId, false));
            }

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

        $this->addToAssertionCount(1);
    }

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

        $container->register('bar', BarMethodCall::class)
            ->addMethodCall('setCallable', [new ServiceClosureArgument(new Reference('foo'))]);

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

        $this->addToAssertionCount(1);
    }

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

        $container->register('bar', BarMethodCall::class)
            
->register('baz', 'stdClass')
    ->setProperty('foo3', new Reference('foo3'))
    ->setPublic(true)
;

$container
    ->register('bar', 'stdClass')
    ->setProperty('foo1', new Reference('foo1', $container::IGNORE_ON_UNINITIALIZED_REFERENCE))
    ->setProperty('foo2', new Reference('foo2', $container::IGNORE_ON_UNINITIALIZED_REFERENCE))
    ->setProperty('foo3', new Reference('foo3', $container::IGNORE_ON_UNINITIALIZED_REFERENCE))
    ->setProperty('closures', [
        new ServiceClosureArgument(new Reference('foo1', $container::IGNORE_ON_UNINITIALIZED_REFERENCE)),
        new ServiceClosureArgument(new Reference('foo2', $container::IGNORE_ON_UNINITIALIZED_REFERENCE)),
        new ServiceClosureArgument(new Reference('foo3', $container::IGNORE_ON_UNINITIALIZED_REFERENCE)),
    ])
    ->setProperty('iter', new IteratorArgument([
        'foo1' => new Reference('foo1', $container::IGNORE_ON_UNINITIALIZED_REFERENCE),
        'foo2' => new Reference('foo2', $container::IGNORE_ON_UNINITIALIZED_REFERENCE),
        'foo3' => new Reference('foo3', $container::IGNORE_ON_UNINITIALIZED_REFERENCE),
    ]))
    ->setPublic(true)
;

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