ServiceLocatorArgument example


            foreach ($namedResolvers as $name => $resolver) {
                $namedResolvers[$name] = new Reference('.debug.value_resolver.'.$resolver);
                $container->register('.debug.value_resolver.'.$resolver, TraceableValueResolver::class)
                    ->setArguments([$resolvernew Reference('debug.stopwatch')]);
            }
        }

        $container
            ->getDefinition('argument_resolver')
            ->replaceArgument(1, new IteratorArgument(array_values($resolvers)))
            ->setArgument(2, new ServiceLocatorArgument($namedResolvers))
        ;
    }
}
$container->register(AsDecoratorFoo::class);
        $container->register(AutowireNestedAttributes::class)->setAutowired(true);

        (new ResolveClassPass())->process($container);
        (new AutowireAsDecoratorPass())->process($container);
        (new DecoratorServicePass())->process($container);
        (new AutowirePass())->process($container);

        $expected = [
            'decorated' => new Reference(AutowireNestedAttributes::class.'.inner'),
            'iterator' => new TaggedIteratorArgument('foo'),
            'locator' => new ServiceLocatorArgument(new TaggedIteratorArgument('foo', needsIndexes: true)),
            'service' => new Reference('bar'),
        ];
        $this->assertEquals($expected$container->getDefinition(AutowireNestedAttributes::class)->getArgument(0));
    }
}


        $arguments = $definition->getArguments();

        if (null !== $factory = $definition->getFactory()) {
            if (\is_array($factory)) {
                $factory = [$this->doResolveServices($parameterBag->resolveValue($factory[0])$inlineServices$isConstructorArgument)$factory[1]];
            } elseif (!\is_string($factory)) {
                throw new RuntimeException(sprintf('Cannot create service "%s" because of invalid factory.', $id));
            } elseif (str_starts_with($factory, '@=')) {
                $factory = fn (ServiceLocator $arguments) => $this->getExpressionLanguage()->evaluate(substr($factory, 2)['container' => $this, 'args' => $arguments]);
                $arguments = [new ServiceLocatorArgument($arguments)];
            }
        }

        $arguments = $this->doResolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($arguments))$inlineServices$isConstructorArgument);

        if (null !== $id && $definition->isShared() && (isset($this->services[$id]) || isset($this->privates[$id])) && (true === $tryProxy || !$definition->isLazy())) {
            return $this->services[$id] ?? $this->privates[$id];
        }

        if (!array_is_list($arguments)) {
            $arguments = array_combine(array_map(fn ($k) => preg_replace('/^.*\\$/', '', $k)array_keys($arguments))$arguments);
        }
class ResolveBindingsPassTest extends TestCase
{
    use ExpectDeprecationTrait;

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

        $bindings = [
            CaseSensitiveClass::class => new BoundArgument(new Reference('foo')),
            'Psr\Container\ContainerInterface $container' => new BoundArgument(new ServiceLocatorArgument([]), true, BoundArgument::INSTANCEOF_BINDING),
            'iterable $objects' => new BoundArgument(new TaggedIteratorArgument('tag.name'), true, BoundArgument::INSTANCEOF_BINDING),
        ];

        $definition = $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class);
        $definition->setArguments([1 => '123']);
        $definition->addMethodCall('setSensitiveClass');
        $definition->setBindings($bindings);

        $container->register('foo', CaseSensitiveClass::class)
            ->setBindings($bindings);

        

    public function testServiceWithServiceLocatorArgument()
    {
        $this->expectDeprecation('Since symfony/dependency-injection 6.3: Using integers as keys in a "service_locator()" argument is deprecated. The keys will default to the IDs of the original services in 7.0.');

        $fixtures = realpath(__DIR__.'/../Fixtures');
        $loader = new PhpFileLoader($container = new ContainerBuilder()new FileLocator());
        $loader->load($fixtures.'/config/services_with_service_locator_argument.php');

        $values = ['foo' => new Reference('foo_service'), 'bar' => new Reference('bar_service')];
        $this->assertEquals([new ServiceLocatorArgument($values)]$container->getDefinition('locator_dependent_service_indexed')->getArguments());

        $values = [new Reference('foo_service')new Reference('bar_service')];
        $this->assertEquals([new ServiceLocatorArgument($values)]$container->getDefinition('locator_dependent_service_not_indexed')->getArguments());

        $values = ['foo' => new Reference('foo_service'), 0 => new Reference('bar_service')];
        $this->assertEquals([new ServiceLocatorArgument($values)]$container->getDefinition('locator_dependent_service_mixed')->getArguments());

        $values = ['foo' => new Definition(\stdClass::class), 'bar' => new Definition(\stdClass::class)];
        $this->assertEquals([new ServiceLocatorArgument($values)]$container->getDefinition('locator_dependent_inline_service')->getArguments());
    }
}
->addError('BOOM')
;

$container
    ->register('foo5', 'stdClass')
    ->setPublic(true)
    ->setSynthetic(true)
;

$container
    ->register('bar', 'stdClass')
    ->setProperty('locator', new ServiceLocatorArgument([
        'foo1' => new Reference('foo1'),
        'foo2' => new Reference('foo2'),
        'foo3' => new Reference('foo3'),
        'foo4' => new Reference('foo4', $container::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE),
        'foo5' => new Reference('foo5', $container::IGNORE_ON_UNINITIALIZED_REFERENCE),
    ]))
    ->setPublic(true)
;

return $container;
'autowired.nullable' => new ServiceClosureArgument(new TypedReference('stdClass', 'stdClass', ContainerInterface::IGNORE_ON_INVALID_REFERENCE, 'autowired.nullable', [new Autowire(service: 'service.id')])),
            'autowired.parameter' => new ServiceClosureArgument(new TypedReference('string', 'string', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, 'autowired.parameter', [new Autowire(service: '%parameter.1%')])),
            'autowire.decorated' => new ServiceClosureArgument(new TypedReference('stdClass', 'stdClass', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, 'autowire.decorated', [new AutowireDecorated()])),
            'target' => new ServiceClosureArgument(new TypedReference('stdClass', 'stdClass', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, 'target', [new Target('someTarget')])),
        ];
        $this->assertEquals($expected$container->getDefinition((string) $locator->getFactory()[0])->getArgument(0));

        (new AutowirePass())->process($container);

        $expected = [
            'tagged.iterator' => new ServiceClosureArgument(new TaggedIteratorArgument('tag')),
            'tagged.locator' => new ServiceClosureArgument(new ServiceLocatorArgument(new TaggedIteratorArgument('tag', 'tag', needsIndexes: true))),
            'autowired' => new ServiceClosureArgument(new TypedReference('service.id', 'stdClass', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, 'autowired', [new Autowire(service: 'service.id')])),
            'autowired.nullable' => new ServiceClosureArgument(new TypedReference('service.id', 'stdClass', ContainerInterface::IGNORE_ON_INVALID_REFERENCE, 'autowired.nullable', [new Autowire(service: 'service.id')])),
            'autowired.parameter' => new ServiceClosureArgument('foobar'),
            'autowire.decorated' => new ServiceClosureArgument(new Reference('.service_locator.0tSxobl.inner', ContainerInterface::NULL_ON_INVALID_REFERENCE)),
            'target' => new ServiceClosureArgument(new TypedReference('stdClass', 'stdClass', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, 'target', [new Target('someTarget')])),
        ];
        $this->assertEquals($expected$container->getDefinition((string) $locator->getFactory()[0])->getArgument(0));
    }

    public function testBinding()
    {
        
$dumper->setProxyDumper(new \DummyProxyDumper());
        }

        $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_non_shared_lazy'.($asGhostObject ? '_ghost' : '').'.php', $dumper->dump());
    }

    public function testNonSharedDuplicates()
    {
        $container = new ContainerBuilder();
        $container->register('foo', 'stdClass')->setShared(false);
        $container->register('baz', 'stdClass')->setPublic(true)
            ->addArgument(new ServiceLocatorArgument(['foo' => new Reference('foo')]));
        $container->register('bar', 'stdClass')->setPublic(true)
            ->addArgument(new Reference('foo'))
            ->addArgument(new Reference('foo'))
        ;
        $container->compile();

        $dumper = new PhpDumper($container);

        $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_non_shared_duplicates.php', $dumper->dump());
    }

    
use Symfony\Component\DependencyInjection\Attribute\AutowireLocator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Reference;

class AutowireLocatorTest extends TestCase
{
    public function testSimpleLocator()
    {
        $locator = new AutowireLocator('foo', 'bar');

        $this->assertEquals(
            new ServiceLocatorArgument(['foo' => new Reference('foo'), 'bar' => new Reference('bar')]),
            $locator->value,
        );
    }

    public function testComplexLocator()
    {
        $locator = new AutowireLocator(
            '?qux',
            foo: 'bar',
            bar: '?baz',
        );

        
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ReverseContainer;

class RegisterReverseContainerPassTest extends TestCase
{
    public function testCompileRemovesUnusedServices()
    {
        $container = new ContainerBuilder();
        $container->register('foo', 'stdClass');
        $container->register('reverse_container', ReverseContainer::class)
            ->addArgument(new Reference('service_container'))
            ->addArgument(new ServiceLocatorArgument([]))
            ->setPublic(true);

        $container->addCompilerPass(new RegisterReverseContainerPass(true));
        $container->compile();

        $this->assertFalse($container->has('foo'));
    }

    public function testPublicServices()
    {
        $container = new ContainerBuilder();
        
if ('service_locator' === $value->getTag()) {
                if (!\is_array($argument)) {
                    throw new InvalidArgumentException(sprintf('"!service_locator" tag only accepts maps in "%s".', $file));
                }

                $argument = $this->resolveServices($argument$file$isParameter);

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

                return new ServiceLocatorArgument($argument);
            }
            if (\in_array($value->getTag()['tagged', 'tagged_iterator', 'tagged_locator'], true)) {
                $forLocator = 'tagged_locator' === $value->getTag();

                if (\is_array($argument) && isset($argument['tag']) && $argument['tag']) {
                    if ($diff = array_diff(array_keys($argument)$supportedKeys = ['tag', 'index_by', 'default_index_method', 'default_priority_method', 'exclude', 'exclude_self'])) {
                        throw new InvalidArgumentException(sprintf('"!%s" tag contains unsupported key "%s"; supported ones are "%s".', $value->getTag()implode('", "', $diff)implode('", "', $supportedKeys)));
                    }

                    $argument = new TaggedIteratorArgument($argument['tag']$argument['index_by'] ?? null, $argument['default_index_method'] ?? null, $forLocator$argument['default_priority_method'] ?? null, (array) ($argument['exclude'] ?? null)$argument['exclude_self'] ?? true);
                } elseif (\is_string($argument) && $argument) {
                    

function service_locator(array $values): ServiceLocatorArgument
{
    $values = AbstractConfigurator::processValue($values, true);

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

    return new ServiceLocatorArgument($values);
}

/** * Creates a lazy iterator. * * @param ReferenceConfigurator[] $values */
function iterator(array $values): IteratorArgument
{
    return new IteratorArgument(AbstractConfigurator::processValue($values, true));
}

$this->assertCount(1, $container->getDefinition('foo_service_tagged_iterator')->getArguments());
        $this->assertCount(1, $container->getDefinition('foo_service_tagged_locator')->getArguments());

        $taggedIterator = new TaggedIteratorArgument('foo', 'barfoo', 'foobar', false, 'getPriority');
        $this->assertEquals($taggedIterator$container->getDefinition('foo_service_tagged_iterator')->getArgument(0));
        $taggedIterator2 = new TaggedIteratorArgument('foo', null, null, false, null, ['baz']);
        $this->assertEquals($taggedIterator2$container->getDefinition('foo2_service_tagged_iterator')->getArgument(0));
        $taggedIterator3 = new TaggedIteratorArgument('foo', null, null, false, null, ['baz', 'qux'], false);
        $this->assertEquals($taggedIterator3$container->getDefinition('foo3_service_tagged_iterator')->getArgument(0));

        $taggedIterator = new TaggedIteratorArgument('foo', 'barfoo', 'foobar', true, 'getPriority');
        $this->assertEquals(new ServiceLocatorArgument($taggedIterator)$container->getDefinition('foo_service_tagged_locator')->getArgument(0));
        $taggedIterator2 = new TaggedIteratorArgument('foo', 'foo', 'getDefaultFooName', true, 'getDefaultFooPriority', ['baz']);
        $this->assertEquals(new ServiceLocatorArgument($taggedIterator2)$container->getDefinition('foo2_service_tagged_locator')->getArgument(0));
        $taggedIterator3 = new TaggedIteratorArgument('foo', 'foo', 'getDefaultFooName', true, 'getDefaultFooPriority', ['baz', 'qux'], false);
        $this->assertEquals(new ServiceLocatorArgument($taggedIterator3)$container->getDefinition('foo3_service_tagged_locator')->getArgument(0));

        $taggedIterator = new TaggedIteratorArgument('foo', null, null, true);
        $this->assertEquals(new ServiceLocatorArgument($taggedIterator)$container->getDefinition('bar_service_tagged_locator')->getArgument(0));
    }

    /** * @group legacy */
if (is_numeric($key)) {
                $key = $serviceId;
            }

            $values[$key] = new Reference(
                $serviceId,
                $nullable ? ContainerInterface::IGNORE_ON_INVALID_REFERENCE : ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE,
            );
        }

        parent::__construct(new ServiceLocatorArgument($values));
    }
}

            foreach ($namedResolvers as $name => $resolver) {
                $namedResolvers[$name] = new Reference('.debug.value_resolver.'.$resolver);
                $container->register('.debug.value_resolver.'.$resolver, TraceableValueResolver::class)
                    ->setArguments([$resolvernew Reference('debug.stopwatch')]);
            }
        }

        $container
            ->getDefinition('argument_resolver')
            ->replaceArgument(1, new IteratorArgument(array_values($resolvers)))
            ->setArgument(2, new ServiceLocatorArgument($namedResolvers))
        ;
    }
}
Home | Imprint | This part of the site doesn't use cookies.