Skip to content

[DI] Add ability to choose behavior of decorations on non existent decorated services #33854

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 3, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Symfony/Component/DependencyInjection/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ CHANGELOG
* added support for improved syntax to define method calls in Yaml
* added `LazyString` for lazy computation of string values injected into services
* made the `%env(base64:...)%` processor able to decode base64url
* added ability to choose behavior of decorations on non existent decorated services

4.3.0
-----
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@

use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
use Symfony\Component\DependencyInjection\Reference;

/**
* Overwrites a service but keeps the overridden one.
Expand All @@ -37,14 +40,17 @@ public function process(ContainerBuilder $container)
$decoratingDefinitions = [];

foreach ($definitions as list($id, $definition)) {
list($inner, $renamedId) = $definition->getDecoratedService();
$decoratedService = $definition->getDecoratedService();
list($inner, $renamedId) = $decoratedService;
$invalidBehavior = $decoratedService[3] ?? ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;

$definition->setDecoratedService(null);

if (!$renamedId) {
$renamedId = $id.'.inner';
}
$definition->innerServiceId = $renamedId;
$definition->decorationOnInvalid = $invalidBehavior;

// we create a new alias/service for the service we are replacing
// to be able to reference it in the new one
Expand All @@ -53,13 +59,21 @@ public function process(ContainerBuilder $container)
$public = $alias->isPublic();
$private = $alias->isPrivate();
$container->setAlias($renamedId, new Alias((string) $alias, false));
} else {
} elseif ($container->hasDefinition($inner)) {
$decoratedDefinition = $container->getDefinition($inner);
$public = $decoratedDefinition->isPublic();
$private = $decoratedDefinition->isPrivate();
$decoratedDefinition->setPublic(false);
$container->setDefinition($renamedId, $decoratedDefinition);
$decoratingDefinitions[$inner] = $decoratedDefinition;
} elseif (ContainerInterface::IGNORE_ON_INVALID_REFERENCE === $invalidBehavior) {
$container->removeDefinition($id);
continue;
} elseif (ContainerInterface::NULL_ON_INVALID_REFERENCE === $invalidBehavior) {
$public = $definition->isPublic();
$private = $definition->isPrivate();
} else {
throw new ServiceNotFoundException($inner, $id);
}

if (isset($decoratingDefinitions[$inner])) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\ExceptionInterface;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
Expand Down Expand Up @@ -149,7 +150,7 @@ private function doResolveDefinition(ChildDefinition $definition): Definition
if (null === $decoratedService) {
$def->setDecoratedService($decoratedService);
} else {
$def->setDecoratedService($decoratedService[0], $decoratedService[1], $decoratedService[2]);
$def->setDecoratedService($decoratedService[0], $decoratedService[1], $decoratedService[2], $decoratedService[3] ?? ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ public function process(ContainerBuilder $container)
$this->signalingException = new RuntimeException('Invalid reference.');

try {
$this->processValue($container->getDefinitions(), 1);
foreach ($container->getDefinitions() as $this->currentId => $definition) {
$this->processValue($definition);
}
} finally {
$this->container = $this->signalingException = null;
}
Expand Down Expand Up @@ -72,9 +74,6 @@ private function processValue($value, int $rootLevel = 0, int $level = 0)
$i = 0;

foreach ($value as $k => $v) {
if (!$rootLevel) {
$this->currentId = $k;
}
try {
if (false !== $i && $k !== $i++) {
$i = false;
Expand All @@ -101,6 +100,14 @@ private function processValue($value, int $rootLevel = 0, int $level = 0)
if ($this->container->has($id = (string) $value)) {
return $value;
}

$currentDefinition = $this->container->getDefinition($this->currentId);

// resolve decorated service behavior depending on decorator service
if ($currentDefinition->innerServiceId === $id && ContainerInterface::NULL_ON_INVALID_REFERENCE === $currentDefinition->decorationOnInvalid) {
return null;
}

$invalidBehavior = $value->getInvalidBehavior();

if (ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior && $value instanceof TypedReference && !$this->container->has($id)) {
Expand Down
22 changes: 18 additions & 4 deletions src/Symfony/Component/DependencyInjection/Definition.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,13 @@ class Definition
*/
public $innerServiceId;

/**
* @internal
*
* Used to store the behavior to follow when using service decoration and the decorated service is invalid
*/
public $decorationOnInvalid;

/**
* @param string|null $class The service class
* @param array $arguments An array of arguments to pass to the service constructor
Expand Down Expand Up @@ -127,26 +134,33 @@ public function getFactory()
/**
* Sets the service that this service is decorating.
*
* @param string|null $id The decorated service id, use null to remove decoration
* @param string|null $renamedId The new decorated service id
* @param int $priority The priority of decoration
* @param string|null $id The decorated service id, use null to remove decoration
* @param string|null $renamedId The new decorated service id
* @param int $priority The priority of decoration
* @param int $invalidBehavior The behavior to adopt when decorated is invalid
*
* @return $this
*
* @throws InvalidArgumentException in case the decorated service id and the new decorated service id are equals
*/
public function setDecoratedService($id, $renamedId = null, $priority = 0)
public function setDecoratedService($id, $renamedId = null, $priority = 0/*, int $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE*/)
{
if ($renamedId && $id === $renamedId) {
throw new InvalidArgumentException(sprintf('The decorated service inner name for "%s" must be different than the service name itself.', $id));
}

$invalidBehavior = 3 < \func_num_args() ? (int) func_get_arg(3) : ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;

$this->changes['decorated_service'] = true;

if (null === $id) {
$this->decoratedService = null;
} else {
$this->decoratedService = [$id, $renamedId, (int) $priority];

if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior) {
$this->decoratedService[] = $invalidBehavior;
}
}

return $this;
Expand Down
10 changes: 8 additions & 2 deletions src/Symfony/Component/DependencyInjection/Dumper/XmlDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,15 @@ private function addService(Definition $definition, ?string $id, \DOMElement $pa
if ($definition->isLazy()) {
$service->setAttribute('lazy', 'true');
}
if (null !== $decorated = $definition->getDecoratedService()) {
list($decorated, $renamedId, $priority) = $decorated;
if (null !== $decoratedService = $definition->getDecoratedService()) {
list($decorated, $renamedId, $priority) = $decoratedService;
$service->setAttribute('decorates', $decorated);

$decorationOnInvalid = $decoratedService[3] ?? ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
if (\in_array($decorationOnInvalid, [ContainerInterface::IGNORE_ON_INVALID_REFERENCE, ContainerInterface::NULL_ON_INVALID_REFERENCE], true)) {
$invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE === $decorationOnInvalid ? 'null' : 'ignore';
$service->setAttribute('decoration-on-invalid', $invalidBehavior);
}
if (null !== $renamedId) {
$service->setAttribute('decoration-inner-name', $renamedId);
}
Expand Down
10 changes: 8 additions & 2 deletions src/Symfony/Component/DependencyInjection/Dumper/YamlDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,15 +131,21 @@ private function addService(string $id, Definition $definition): string
$code .= " shared: false\n";
}

if (null !== $decorated = $definition->getDecoratedService()) {
list($decorated, $renamedId, $priority) = $decorated;
if (null !== $decoratedService = $definition->getDecoratedService()) {
list($decorated, $renamedId, $priority) = $decoratedService;
$code .= sprintf(" decorates: %s\n", $decorated);
if (null !== $renamedId) {
$code .= sprintf(" decoration_inner_name: %s\n", $renamedId);
}
if (0 !== $priority) {
$code .= sprintf(" decoration_priority: %s\n", $priority);
}

$decorationOnInvalid = $decoratedService[3] ?? ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
if (\in_array($decorationOnInvalid, [ContainerInterface::IGNORE_ON_INVALID_REFERENCE, ContainerInterface::NULL_ON_INVALID_REFERENCE])) {
$invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE === $decorationOnInvalid ? 'null' : 'ignore';
$code .= sprintf(" decoration_on_invalid: %s\n", $invalidBehavior);
}
}

if ($callable = $definition->getFactory()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,26 @@

namespace Symfony\Component\DependencyInjection\Loader\Configurator\Traits;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;

trait DecorateTrait
{
/**
* Sets the service that this service is decorating.
*
* @param string|null $id The decorated service id, use null to remove decoration
* @param string|null $id The decorated service id, use null to remove decoration
* @param string|null $renamedId The new decorated service id
* @param int $priority The priority of decoration
* @param int $invalidBehavior The behavior to adopt when decorated is invalid
*
* @return $this
*
* @throws InvalidArgumentException in case the decorated service id and the new decorated service id are equals
*/
final public function decorate(?string $id, string $renamedId = null, int $priority = 0): self
final public function decorate(?string $id, string $renamedId = null, int $priority = 0, int $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE): self
{
$this->definition->setDecoratedService($id, $renamedId, $priority);
$this->definition->setDecoratedService($id, $renamedId, $priority, $invalidBehavior);

return $this;
}
Expand Down
16 changes: 14 additions & 2 deletions src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -362,10 +362,22 @@ private function parseDefinition(\DOMElement $service, string $file, array $defa
$definition->setBindings($bindings);
}

if ($value = $service->getAttribute('decorates')) {
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 InvalidArgumentException(sprintf('Invalid value "%s" for attribute "decoration-on-invalid" on service "%s". Did you mean "exception", "ignore" or "null" in "%s"?', $decorationOnInvalid, (string) $service->getAttribute('id'), $file));
}

$renameId = $service->hasAttribute('decoration-inner-name') ? $service->getAttribute('decoration-inner-name') : null;
$priority = $service->hasAttribute('decoration-priority') ? $service->getAttribute('decoration-priority') : 0;
$definition->setDecoratedService($value, $renameId, $priority);

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

return $definition;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ class YamlFileLoader extends FileLoader
'decorates' => 'decorates',
'decoration_inner_name' => 'decoration_inner_name',
'decoration_priority' => 'decoration_priority',
'decoration_on_invalid' => 'decoration_on_invalid',
'autowire' => 'autowire',
'autoconfigure' => 'autoconfigure',
'bind' => 'bind',
Expand Down Expand Up @@ -538,14 +539,28 @@ private function parseDefinition(string $id, $service, string $file, array $defa
$definition->addTag($name, $tag);
}

if (isset($service['decorates'])) {
if ('' !== $service['decorates'] && '@' === $service['decorates'][0]) {
throw new InvalidArgumentException(sprintf('The value of the "decorates" option for the "%s" service must be the id of the service without the "@" prefix (replace "%s" with "%s").', $id, $service['decorates'], substr($service['decorates'], 1)));
if (null !== $decorates = $service['decorates'] ?? null) {
if ('' !== $decorates && '@' === $decorates[0]) {
throw new InvalidArgumentException(sprintf('The value of the "decorates" option for the "%s" service must be the id of the service without the "@" prefix (replace "%s" with "%s").', $id, $service['decorates'], substr($decorates, 1)));
}

$decorationOnInvalid = \array_key_exists('decoration_on_invalid', $service) ? $service['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;
} elseif ('null' === $decorationOnInvalid) {
throw new InvalidArgumentException(sprintf('Invalid value "%s" for attribute "decoration_on_invalid" on service "%s". Did you mean null (without quotes) in "%s"?', $decorationOnInvalid, $id, $file));
} else {
throw new InvalidArgumentException(sprintf('Invalid value "%s" for attribute "decoration_on_invalid" on service "%s". Did you mean "exception", "ignore" or null in "%s"?', $decorationOnInvalid, $id, $file));
}

$renameId = isset($service['decoration_inner_name']) ? $service['decoration_inner_name'] : null;
$priority = isset($service['decoration_priority']) ? $service['decoration_priority'] : 0;
$definition->setDecoratedService($service['decorates'], $renameId, $priority);

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

if (isset($service['autowire'])) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="parent" type="xsd:string" />
<xsd:attribute name="decorates" type="xsd:string" />
<xsd:attribute name="decoration-on-invalid" type="invalid_decorated_service_sequence" />
<xsd:attribute name="decoration-inner-name" type="xsd:string" />
<xsd:attribute name="decoration-priority" type="xsd:integer" />
<xsd:attribute name="autowire" type="boolean" />
Expand Down Expand Up @@ -281,6 +282,14 @@
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name="invalid_decorated_service_sequence">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="null" />
<xsd:enumeration value="ignore" />
<xsd:enumeration value="exception" />
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name="boolean">
<xsd:restriction base="xsd:string">
<xsd:pattern value="(%.+%|true|false)" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Compiler\DecoratorServicePass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;

class DecoratorServicePassTest extends TestCase
{
Expand Down Expand Up @@ -125,6 +126,61 @@ public function testProcessWithPriority()
$this->assertNull($quxDefinition->getDecoratedService());
}

public function testProcessWithInvalidDecorated()
{
$container = new ContainerBuilder();
$decoratorDefinition = $container
->register('decorator')
->setDecoratedService('unknown_decorated', null, 0, ContainerInterface::IGNORE_ON_INVALID_REFERENCE)
;

$this->process($container);
$this->assertFalse($container->has('decorator'));

$container = new ContainerBuilder();
$decoratorDefinition = $container
->register('decorator')
->setDecoratedService('unknown_decorated', null, 0, ContainerInterface::NULL_ON_INVALID_REFERENCE)
;

$this->process($container);
$this->assertTrue($container->has('decorator'));
$this->assertSame(ContainerInterface::NULL_ON_INVALID_REFERENCE, $decoratorDefinition->decorationOnInvalid);

$container = new ContainerBuilder();
$decoratorDefinition = $container
->register('decorator')
->setDecoratedService('unknown_service')
;

$this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException');
$this->process($container);
}

public function testProcessNoInnerAliasWithInvalidDecorated()
{
$container = new ContainerBuilder();
$decoratorDefinition = $container
->register('decorator')
->setDecoratedService('unknown_decorated', null, 0, ContainerInterface::NULL_ON_INVALID_REFERENCE)
;

$this->process($container);
$this->assertFalse($container->hasAlias('decorator.inner'));
}

public function testProcessWithInvalidDecoratedAndWrongBehavior()
{
$container = new ContainerBuilder();
$decoratorDefinition = $container
->register('decorator')
->setDecoratedService('unknown_decorated', null, 0, 12)
;

$this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException');
$this->process($container);
}

public function testProcessMovesTagsFromDecoratedDefinitionToDecoratingDefinition()
{
$container = new ContainerBuilder();
Expand Down
Loading