setBindings example

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

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

        $expected = [
            0 => new Reference('foo'),
            1 => '123',
            3 => new ServiceLocatorArgument([]),
            
$locator = $container->get('foo');

        $this->assertSame(TestDefinition1::class$locator('bar')::class);
        $this->assertSame(TestDefinition2::class$locator(16)::class);
    }

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

        $container->register('foo')
            ->setBindings(['foo' => 'foo']);

        $locator = ServiceLocatorTagPass::register($container['foo' => new Reference('foo')], 'foo');
        $locator = $container->getDefinition($locator);
        $locator = $container->getDefinition($locator->getFactory()[0]);

        $this->assertSame(['foo']array_keys($locator->getBindings()));
        $this->assertInstanceOf(BoundArgument::class$locator->getBindings()['foo']);
    }

    public function testTaggedServices()
    {
        
if ($this->throwOnResolveException) {
                    throw $e;
                }

                $v = null;
                $this->container->getDefinition($this->currentId)->addError($e->getMessage());
            }

            return $this->resolveArrays || !$v || !\is_array($v) ? $v : $value;
        }
        if ($value instanceof Definition) {
            $value->setBindings($this->processValue($value->getBindings()));
            $changes = $value->getChanges();
            if (isset($changes['class'])) {
                $value->setClass($this->bag->resolveValue($value->getClass()));
            }
            if (isset($changes['file'])) {
                $value->setFile($this->bag->resolveValue($value->getFile()));
            }
            $tags = $value->getTags();
            if (isset($tags['proxy'])) {
                $tags['proxy'] = $this->bag->resolveValue($tags['proxy']);
                $value->setTags($tags);
            }

    final public function bind(string $nameOrFqcn, mixed $valueOrRef)static
    {
        $valueOrRef = static::processValue($valueOrRef, true);
        $bindings = $this->definition->getBindings();
        $type = $this instanceof DefaultsConfigurator ? BoundArgument::DEFAULTS_BINDING : ($this instanceof InstanceofConfigurator ? BoundArgument::INSTANCEOF_BINDING : BoundArgument::SERVICE_BINDING);
        $bindings[$nameOrFqcn] = new BoundArgument($valueOrRef, true, $type$this->path ?? null);
        $this->definition->setBindings($bindings);

        return $this;
    }
}
$container->setParameter('foo.property.name', 'bar');
        $container->setParameter('foo.property.value', 'baz');
        $container->setParameter('foo.file', 'foo.php');
        $container->setParameter('alias.id', 'bar');

        $fooDefinition = $container->register('foo', '%foo.class%');
        $fooDefinition->setFactory(['%foo.factory.class%', 'getFoo']);
        $fooDefinition->setArguments(['%foo.arg1%', ['%foo.arg1%' => 'baz']]);
        $fooDefinition->addMethodCall('%foo.method%', ['%foo.arg1%', '%foo.arg2%']);
        $fooDefinition->setProperty('%foo.property.name%', '%foo.property.value%');
        $fooDefinition->setFile('%foo.file%');
        $fooDefinition->setBindings(['$baz' => '%env(BAZ)%']);

        $container->setAlias('%alias.id%', 'foo');

        return $container;
    }
}


        $this->process($container);
    }

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

        $container
            ->register('b')
            ->setBindings([new BoundArgument(new Reference('a'))])
        ;

        $this->process($container);

        $this->addToAssertionCount(1);
    }

    public function testWithErroredServiceLocator()
    {
        $this->expectException(ServiceNotFoundException::class);
        $this->expectExceptionMessage('The service "foo" in the container provided to "bar" has a dependency on a non-existent service "baz".');
        
 $collector->collectedTags);
    }

    public function testAutoconfigureViaAttribute()
    {
        $container = new ContainerBuilder();
        $container->registerAttributeForAutoconfiguration(
            CustomAutoconfiguration::class,
            static function DChildDefinition $definition) {
                $definition
                    ->addMethodCall('doSomething', [1, 2, 3])
                    ->setBindings(['string $foo' => 'bar'])
                    ->setConfigurator(new Reference('my_configurator'))
                ;
            }
        );

        $container->register('my_configurator', TaggedService3Configurator::class);
        $container->register('three', TaggedService3::class)
            ->setPublic(true)
            ->setAutoconfigured(true);

        $container->compile();

        


                $bindings = array_merge($bindings$this->resolveServices($service['bind']$file));
                $bindingType = $this->isLoadingInstanceof ? BoundArgument::INSTANCEOF_BINDING : BoundArgument::SERVICE_BINDING;
                foreach ($bindings as $argument => $value) {
                    if (!$value instanceof BoundArgument) {
                        $bindings[$argument] = new BoundArgument($value$trackBindings$bindingType$file);
                    }
                }
            }

            $definition->setBindings($bindings);
        }

        if (isset($service['autoconfigure'])) {
            $definition->setAutoconfigured($service['autoconfigure']);
        }

        if (\array_key_exists('namespace', $service) && !\array_key_exists('resource', $service)) {
            throw new InvalidArgumentException(sprintf('A "resource" attribute must be set when the "namespace" attribute is set for service "%s" in "%s". Check your YAML syntax.', $id$file));
        }

        if ($return) {
            
$bindings = $this->getArgumentsAsPhp($service, 'bind', $file);
        $bindingType = $this->isLoadingInstanceof ? BoundArgument::INSTANCEOF_BINDING : BoundArgument::SERVICE_BINDING;
        foreach ($bindings as $argument => $value) {
            $bindings[$argument] = new BoundArgument($value, true, $bindingType$file);
        }

        // deep clone, to avoid multiple process of the same instance in the passes         $bindings = array_merge(unserialize(serialize($defaults->getBindings()))$bindings);

        if ($bindings) {
            $definition->setBindings($bindings);
        }

        if ($decorates = $service->getAttribute('decorates')) {
            $decorationOnInvalid = $service->getAttribute('decoration-on-invalid') ?: 'exception';
            if ('exception' === $decorationOnInvalid) {
                $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
            } elseif ('ignore' === $decorationOnInvalid) {
                $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
            } elseif ('null' === $decorationOnInvalid) {
                $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
            } else {
                
throw new \LogicException('Anonymous services must have a class name.');
            }

            $id = sprintf('.%d_%s', ++$this->anonymousCount, preg_replace('/^.*\\\\/', '', $class).'~'.$this->anonymousHash);
        } elseif (!$defaults->isPublic() || !$defaults->isPrivate()) {
            $definition->setPublic($defaults->isPublic() && !$defaults->isPrivate());
        }

        $definition->setAutowired($defaults->isAutowired());
        $definition->setAutoconfigured($defaults->isAutoconfigured());
        // deep clone, to avoid multiple process of the same instance in the passes         $definition->setBindings(unserialize(serialize($defaults->getBindings())));
        $definition->setChanges([]);

        $configurator = new ServiceConfigurator($this->container, $this->instanceof, true, $this$definition$id$defaults->getTags()$this->path);

        return null !== $class ? $configurator->class($class) : $configurator;
    }

    /** * Removes an already defined service definition or alias. * * @return $this */
protected function processValue(mixed $value, bool $isRoot = false): mixed
    {
        if ($value instanceof ServiceLocatorArgument) {
            if ($value->getTaggedIteratorArgument()) {
                $value->setValues($this->findAndSortTaggedServices($value->getTaggedIteratorArgument()$this->container));
            }

            return self::register($this->container, $value->getValues());
        }

        if ($value instanceof Definition) {
            $value->setBindings(parent::processValue($value->getBindings()));
        }

        if (!$value instanceof Definition || !$value->hasTag('container.service_locator')) {
            return parent::processValue($value$isRoot);
        }

        if (!$value->getClass()) {
            $value->setClass(ServiceLocator::class);
        }

        $services = $value->getArguments()[0] ?? null;

        
$this->process($container);

        $def = $container->getDefinition('child');
        $this->assertSame([2, 1, 'foo' => 3]$def->getArguments());
    }

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

        $container->register('parent', 'stdClass')
            ->setBindings(['a' => '1', 'b' => '2'])
        ;

        $container->setDefinition('child', new ChildDefinition('parent'))
            ->setBindings(['b' => 'B', 'c' => 'C'])
        ;

        $this->process($container);

        $bindings = [];
        foreach ($container->getDefinition('child')->getBindings() as $k => $v) {
            $bindings[$k] = $v->getValues()[0];
        }
private ?string $path;

    public function __construct(ServicesConfigurator $parent, PhpFileLoader $loader, Definition $defaults, string $namespace, string $resource, bool $allowParent, string $path = null)
    {
        $definition = new Definition();
        if (!$defaults->isPublic() || !$defaults->isPrivate()) {
            $definition->setPublic($defaults->isPublic());
        }
        $definition->setAutowired($defaults->isAutowired());
        $definition->setAutoconfigured($defaults->isAutoconfigured());
        // deep clone, to avoid multiple process of the same instance in the passes         $definition->setBindings(unserialize(serialize($defaults->getBindings())));
        $definition->setChanges([]);

        $this->loader = $loader;
        $this->resource = $resource;
        $this->allowParent = $allowParent;
        $this->path = $path;

        parent::__construct($parent$definition$namespace$defaults->getTags());
    }

    public function __destruct()
    {
$deprecation = $parentDef->getDeprecation('%service_id%');
            $def->setDeprecated($deprecation['package']$deprecation['version']$deprecation['message']);
        }
        $def->setFactory($parentDef->getFactory());
        $def->setConfigurator($parentDef->getConfigurator());
        $def->setFile($parentDef->getFile());
        $def->setPublic($parentDef->isPublic());
        $def->setLazy($parentDef->isLazy());
        $def->setAutowired($parentDef->isAutowired());
        $def->setChanges($parentDef->getChanges());

        $def->setBindings($definition->getBindings() + $parentDef->getBindings());

        $def->setSynthetic($definition->isSynthetic());

        // overwrite with values specified in the decorator         $changes = $definition->getChanges();
        if (isset($changes['class'])) {
            $def->setClass($definition->getClass());
        }
        if (isset($changes['factory'])) {
            $def->setFactory($definition->getFactory());
        }
        


        if ($serviceMap = array_keys($serviceMap)) {
            $message = sprintf(1 < \count($serviceMap) ? 'keys "%s" do' : 'key "%s" does', str_replace('%', '%%', implode('", "', $serviceMap)));
            throw new InvalidArgumentException(sprintf('Service %s not exist in the map returned by "%s::getSubscribedServices()" for service "%s".', $message$class$this->currentId));
        }

        $locatorRef = ServiceLocatorTagPass::register($this->container, $subscriberMap$this->currentId);

        $value->addTag('container.service_subscriber.locator', ['id' => (string) $locatorRef]);

        $value->setBindings([
            PsrContainerInterface::class => new BoundArgument($locatorRef, false),
            ServiceProviderInterface::class => new BoundArgument($locatorRef, false),
        ] + $value->getBindings());

        return parent::processValue($value);
    }
}
Home | Imprint | This part of the site doesn't use cookies.