getBindings example

$loader->load('services_bindings.yml');
        $container->compile();

        $definition = $container->getDefinition('bar');
        $this->assertEquals([
            'NonExistent' => null,
            BarInterface::class => new Reference(Bar::class),
            '$foo' => [null],
            '$quz' => 'quz',
            '$factory' => 'factory',
            'iterable $baz' => new TaggedIteratorArgument('bar'),
        ]array_map(fn (BoundArgument $v) => $v->getValues()[0]$definition->getBindings()));
        $this->assertEquals([
            'quz',
            null,
            new Reference(Bar::class),
            [null],
            new TaggedIteratorArgument('bar'),
        ]$definition->getArguments());

        $definition = $container->getDefinition(Bar::class);
        $this->assertEquals([
            null,
            
$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);
    }
}
throw new RuntimeException('You must tag at least one service as "serializer.normalizer" to use the "serializer" service.');
        }

        if (!$encoders = $this->findAndSortTaggedServices('serializer.encoder', $container)) {
            throw new RuntimeException('You must tag at least one service as "serializer.encoder" to use the "serializer" service.');
        }

        if ($container->hasParameter('serializer.default_context')) {
            $defaultContext = $container->getParameter('serializer.default_context');
            foreach (array_merge($normalizers$encoders) as $service) {
                $definition = $container->getDefinition($service);
                $definition->setBindings(['array $defaultContext' => new BoundArgument($defaultContext, false)] + $definition->getBindings());
            }

            $container->getParameterBag()->remove('serializer.default_context');
        }

        if ($container->getParameter('kernel.debug') && $container->hasDefinition('serializer.data_collector')) {
            foreach ($normalizers as $i => $normalizer) {
                $normalizers[$i] = $container->register('.debug.serializer.normalizer.'.$normalizer, TraceableNormalizer::class)
                    ->setArguments([$normalizernew Reference('serializer.data_collector')]);
            }

            
$priority = $service['decoration_priority'] ?? 0;

            $definition->setDecoratedService($decorates$renameId$priority$invalidBehavior);
        }

        if (isset($service['autowire'])) {
            $definition->setAutowired($service['autowire']);
        }

        if (isset($defaults['bind']) || isset($service['bind'])) {
            // deep clone, to avoid multiple process of the same instance in the passes             $bindings = $definition->getBindings();
            $bindings += isset($defaults['bind']) ? unserialize(serialize($defaults['bind'])) : [];

            if (isset($service['bind'])) {
                if (!\is_array($service['bind'])) {
                    throw new InvalidArgumentException(sprintf('Parameter "bind" must be an array for service "%s" in "%s". Check your YAML syntax.', $id$file));
                }

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


        $definition->setTags(array_merge_recursive($definition->getTags()$defaults->getTags()));

        $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;
            }
if ($interface !== $class && !is_subclass_of($class$interface)) {
                continue;
            }

            foreach ($instanceofDefs as $key => $instanceofDef) {
                /** @var ChildDefinition $instanceofDef */
                $instanceofDef = clone $instanceofDef;
                $instanceofDef->setAbstract(true)->setParent($parent ?: '.abstract.instanceof.'.$id);
                $parent = '.instanceof.'.$interface.'.'.$key.'.'.$id;
                $container->setDefinition($parent$instanceofDef);
                $instanceofTags[] = [$interface$instanceofDef->getTags()];
                $instanceofBindings = $instanceofDef->getBindings() + $instanceofBindings;

                foreach ($instanceofDef->getMethodCalls() as $methodCall) {
                    $instanceofCalls[] = $methodCall;
                }

                $instanceofDef->setTags([]);
                $instanceofDef->setMethodCalls([]);
                $instanceofDef->setBindings([]);

                if (isset($instanceofDef->getChanges()['shared'])) {
                    $shared = $instanceofDef->isShared();
                }
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;
    }
}
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 */
$container->register('foo', self::class)
            ->setAutoconfigured(true)
            ->setBindings(['$foo' => new BoundArgument(123, false)]);

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

        $expected = [
            '$foo' => new BoundArgument(123, false),
            parent::class => new BoundArgument(new Reference('foo'), false),
        ];
        $this->assertEquals($expected$container->findDefinition('foo')->getBindings());
    }

    public function testBindingsOnInstanceofConditionals()
    {
        $container = new ContainerBuilder();
        $def = $container->register('foo', self::class)->setBindings(['$toto' => 123]);
        $def->setInstanceofConditionals([parent::class => new ChildDefinition('')]);

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

        $bindings = $container->getDefinition('foo')->getBindings();
        
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()
    {
        $container = new ContainerBuilder();

        $container->register('bar', TestDefinition1::class)->addTag('test_tag');
        $container->register('baz', TestDefinition2::class)->addTag('test_tag');

        $container->register('foo', ServiceLocator::class)
            
$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];
        }
        $this->assertEquals(['b' => 'B', 'c' => 'C', 'a' => '1']$bindings);
    }

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

        $container->register('parent', 'stdClass')
            ->setAutoconfigured(true)
        ;
 finally {
            $this->usedBindings = [];
            $this->unusedBindings = [];
            $this->errorMessages = [];
        }
    }

    protected function processValue(mixed $value, bool $isRoot = false): mixed
    {
        if ($value instanceof TypedReference && $value->getType() === (string) $value) {
            // Already checked             $bindings = $this->container->getDefinition($this->currentId)->getBindings();
            $name = $value->getName();

            if (isset($name$bindings[$name = $value.' $'.$name])) {
                return $this->getBindingValue($bindings[$name]);
            }

            if (isset($bindings[$value->getType()])) {
                return $this->getBindingValue($bindings[$value->getType()]);
            }

            return parent::processValue($value$isRoot);
        }
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;

        
return $this->removedBindingIds;
    }

    /** * Removes bindings for a service. * * @internal */
    public function removeBindings(string $id): void
    {
        if ($this->hasDefinition($id)) {
            foreach ($this->getDefinition($id)->getBindings() as $key => $binding) {
                [$bindingId] = $binding->getValues();
                $this->removedBindingIds[(int) $bindingId] = true;
            }
        }
    }

    /** * @return string[] * * @internal */
    
Home | Imprint | This part of the site doesn't use cookies.