Skip to content
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
[DependencyInjection] Enable multiple attribute autoconfiguration cal…
…lbacks on the same class
  • Loading branch information
GromNaN authored and nicolas-grekas committed Mar 21, 2025
commit e36fe60628ce8bc8008923afb5dab9b95560c860
5 changes: 5 additions & 0 deletions UPGRADE-7.3.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ Console

* Deprecate methods `Command::getDefaultName()` and `Command::getDefaultDescription()` in favor of the `#[AsCommand]` attribute

DependencyInjection
-------------------

* Deprecate `ContainerBuilder::getAutoconfiguredAttributes()` in favor of the `getAttributeAutoconfigurators()` method.

FrameworkBundle
---------------

Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/DependencyInjection/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ CHANGELOG
* Don't skip classes with private constructor when autodiscovering
* Add `Definition::addResourceTag()` and `ContainerBuilder::findTaggedResourceIds()`
for auto-configuration of classes excluded from the service container
* Accept multiple auto-configuration callbacks for the same attribute class
* Leverage native lazy objects when possible for lazy services

7.2
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,49 +31,51 @@ final class AttributeAutoconfigurationPass extends AbstractRecursivePass

public function process(ContainerBuilder $container): void
{
if (!$container->getAutoconfiguredAttributes()) {
if (!$container->getAttributeAutoconfigurators()) {
return;
}

foreach ($container->getAutoconfiguredAttributes() as $attributeName => $callable) {
$callableReflector = new \ReflectionFunction($callable(...));
if ($callableReflector->getNumberOfParameters() <= 2) {
$this->classAttributeConfigurators[$attributeName] = $callable;
continue;
}
foreach ($container->getAttributeAutoconfigurators() as $attributeName => $callables) {
foreach ($callables as $callable) {
$callableReflector = new \ReflectionFunction($callable(...));
if ($callableReflector->getNumberOfParameters() <= 2) {
$this->classAttributeConfigurators[$attributeName][] = $callable;
continue;
}

$reflectorParameter = $callableReflector->getParameters()[2];
$parameterType = $reflectorParameter->getType();
$types = [];
if ($parameterType instanceof \ReflectionUnionType) {
foreach ($parameterType->getTypes() as $type) {
$types[] = $type->getName();
$reflectorParameter = $callableReflector->getParameters()[2];
$parameterType = $reflectorParameter->getType();
$types = [];
if ($parameterType instanceof \ReflectionUnionType) {
foreach ($parameterType->getTypes() as $type) {
$types[] = $type->getName();
}
} elseif ($parameterType instanceof \ReflectionNamedType) {
$types[] = $parameterType->getName();
} else {
throw new LogicException(\sprintf('Argument "$%s" of attribute autoconfigurator should have a type, use one or more of "\ReflectionClass|\ReflectionMethod|\ReflectionProperty|\ReflectionParameter|\Reflector" in "%s" on line "%d".', $reflectorParameter->getName(), $callableReflector->getFileName(), $callableReflector->getStartLine()));
}
} elseif ($parameterType instanceof \ReflectionNamedType) {
$types[] = $parameterType->getName();
} else {
throw new LogicException(\sprintf('Argument "$%s" of attribute autoconfigurator should have a type, use one or more of "\ReflectionClass|\ReflectionMethod|\ReflectionProperty|\ReflectionParameter|\Reflector" in "%s" on line "%d".', $reflectorParameter->getName(), $callableReflector->getFileName(), $callableReflector->getStartLine()));
}

try {
$attributeReflector = new \ReflectionClass($attributeName);
} catch (\ReflectionException) {
continue;
}
try {
$attributeReflector = new \ReflectionClass($attributeName);
} catch (\ReflectionException) {
continue;
}

$targets = $attributeReflector->getAttributes(\Attribute::class)[0] ?? 0;
$targets = $targets ? $targets->getArguments()[0] ?? -1 : 0;
$targets = $attributeReflector->getAttributes(\Attribute::class)[0] ?? 0;
$targets = $targets ? $targets->getArguments()[0] ?? -1 : 0;

foreach (['class', 'method', 'property', 'parameter'] as $symbol) {
if (['Reflector'] !== $types) {
if (!\in_array('Reflection'.ucfirst($symbol), $types, true)) {
continue;
}
if (!($targets & \constant('Attribute::TARGET_'.strtoupper($symbol)))) {
throw new LogicException(\sprintf('Invalid type "Reflection%s" on argument "$%s": attribute "%s" cannot target a '.$symbol.' in "%s" on line "%d".', ucfirst($symbol), $reflectorParameter->getName(), $attributeName, $callableReflector->getFileName(), $callableReflector->getStartLine()));
foreach (['class', 'method', 'property', 'parameter'] as $symbol) {
if (['Reflector'] !== $types) {
if (!\in_array('Reflection' . ucfirst($symbol), $types, true)) {
continue;
}
if (!($targets & \constant('Attribute::TARGET_' . strtoupper($symbol)))) {
throw new LogicException(\sprintf('Invalid type "Reflection%s" on argument "$%s": attribute "%s" cannot target a ' . $symbol . ' in "%s" on line "%d".', ucfirst($symbol), $reflectorParameter->getName(), $attributeName, $callableReflector->getFileName(), $callableReflector->getStartLine()));
}
}
$this->{$symbol . 'AttributeConfigurators'}[$attributeName][] = $callable;
}
$this->{$symbol.'AttributeConfigurators'}[$attributeName] = $callable;
}
}

Expand All @@ -94,13 +96,7 @@ protected function processValue(mixed $value, bool $isRoot = false): mixed
$instanceof = $value->getInstanceofConditionals();
$conditionals = $instanceof[$classReflector->getName()] ?? new ChildDefinition('');

if ($this->classAttributeConfigurators) {
foreach ($classReflector->getAttributes() as $attribute) {
if ($configurator = $this->findConfigurator($this->classAttributeConfigurators, $attribute->getName())) {
$configurator($conditionals, $attribute->newInstance(), $classReflector);
}
}
}
$this->callConfigurators($this->classAttributeConfigurators, $conditionals, $classReflector);

if ($this->parameterAttributeConfigurators) {
try {
Expand All @@ -111,11 +107,7 @@ protected function processValue(mixed $value, bool $isRoot = false): mixed

if ($constructorReflector) {
foreach ($constructorReflector->getParameters() as $parameterReflector) {
foreach ($parameterReflector->getAttributes() as $attribute) {
if ($configurator = $this->findConfigurator($this->parameterAttributeConfigurators, $attribute->getName())) {
$configurator($conditionals, $attribute->newInstance(), $parameterReflector);
}
}
$this->callConfigurators($this->parameterAttributeConfigurators, $conditionals, $parameterReflector);
}
}
}
Expand All @@ -126,22 +118,10 @@ protected function processValue(mixed $value, bool $isRoot = false): mixed
continue;
}

if ($this->methodAttributeConfigurators) {
foreach ($methodReflector->getAttributes() as $attribute) {
if ($configurator = $this->findConfigurator($this->methodAttributeConfigurators, $attribute->getName())) {
$configurator($conditionals, $attribute->newInstance(), $methodReflector);
}
}
}
$this->callConfigurators($this->methodAttributeConfigurators, $conditionals, $methodReflector);

if ($this->parameterAttributeConfigurators) {
foreach ($methodReflector->getParameters() as $parameterReflector) {
foreach ($parameterReflector->getAttributes() as $attribute) {
if ($configurator = $this->findConfigurator($this->parameterAttributeConfigurators, $attribute->getName())) {
$configurator($conditionals, $attribute->newInstance(), $parameterReflector);
}
}
}
foreach ($methodReflector->getParameters() as $parameterReflector) {
$this->callConfigurators($this->parameterAttributeConfigurators, $conditionals, $parameterReflector);
}
}
}
Expand All @@ -152,11 +132,7 @@ protected function processValue(mixed $value, bool $isRoot = false): mixed
continue;
}

foreach ($propertyReflector->getAttributes() as $attribute) {
if ($configurator = $this->findConfigurator($this->propertyAttributeConfigurators, $attribute->getName())) {
$configurator($conditionals, $attribute->newInstance(), $propertyReflector);
}
}
$this->callConfigurators($this->propertyAttributeConfigurators, $conditionals, $propertyReflector);
}
}

Expand All @@ -168,19 +144,37 @@ protected function processValue(mixed $value, bool $isRoot = false): mixed
return parent::processValue($value, $isRoot);
}

/**
* Call all the configurators for the given attribute.
*
* @param array<class-string, callable[]> $configurators
*/
private function callConfigurators(array &$configurators, ChildDefinition $conditionals, \ReflectionClass|\ReflectionMethod|\ReflectionParameter|\ReflectionProperty $reflector): void
{
if (!$configurators) {
return;
}

foreach ($reflector->getAttributes() as $attribute) {
foreach ($this->findConfigurators($configurators, $attribute->getName()) as $configurator) {
$configurator($conditionals, $attribute->newInstance(), $reflector);
}
}
}

/**
* Find the first configurator for the given attribute name, looking up the class hierarchy.
*/
private function findConfigurator(array &$configurators, string $attributeName): ?callable
private function findConfigurators(array &$configurators, string $attributeName): array
{
if (\array_key_exists($attributeName, $configurators)) {
return $configurators[$attributeName];
}

if (class_exists($attributeName) && $parent = get_parent_class($attributeName)) {
return $configurators[$attributeName] = self::findConfigurator($configurators, $parent);
return $configurators[$attributeName] = $this->findConfigurators($configurators, $parent);
}

return $configurators[$attributeName] = null;
return $configurators[$attributeName] = [];
}
}
38 changes: 29 additions & 9 deletions src/Symfony/Component/DependencyInjection/ContainerBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
private array $autoconfiguredInstanceof = [];

/**
* @var array<string, callable>
* @var array<string, callable[]>
*/
private array $autoconfiguredAttributes = [];

Expand Down Expand Up @@ -717,12 +717,11 @@ public function merge(self $container): void
$this->autoconfiguredInstanceof[$interface] = $childDefinition;
}

foreach ($container->getAutoconfiguredAttributes() as $attribute => $configurator) {
if (isset($this->autoconfiguredAttributes[$attribute])) {
throw new InvalidArgumentException(\sprintf('"%s" has already been autoconfigured and merge() does not support merging autoconfiguration for the same attribute.', $attribute));
}

$this->autoconfiguredAttributes[$attribute] = $configurator;
foreach ($container->getAttributeAutoconfigurators() as $attribute => $configurators) {
$this->autoconfiguredAttributes[$attribute] = array_merge(
$this->autoconfiguredAttributes[$attribute] ?? [],
$configurators)
;
}
}

Expand Down Expand Up @@ -1448,7 +1447,7 @@ public function registerForAutoconfiguration(string $interface): ChildDefinition
*/
public function registerAttributeForAutoconfiguration(string $attributeClass, callable $configurator): void
{
$this->autoconfiguredAttributes[$attributeClass] = $configurator;
$this->autoconfiguredAttributes[$attributeClass][] = $configurator;
Copy link
Member Author

@GromNaN GromNaN Mar 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a behavior change: before, it was possible to call registerAttributeForAutoconfiguration() multiple times, replacing the previous configuration. With this change, they are added.

I don't know yet how to handle that, exempt if we allow multiple configurators only by merging.

}

/**
Expand Down Expand Up @@ -1489,9 +1488,30 @@ public function getAutoconfiguredInstanceof(): array
}

/**
* @return array<string, callable>
* @return array<class-string, callable>
*
* @deprecated Use {@see getAttributeAutoconfigurators()} instead
*/
public function getAutoconfiguredAttributes(): array
{
trigger_deprecation('symfony/dependency-injection', '7.3', 'The "%s()" method is deprecated, use "getAttributeAutoconfigurators()" instead.', __METHOD__);

$autoconfiguredAttributes = [];
foreach ($this->autoconfiguredAttributes as $attribute => $configurators) {
if (count($configurators) > 1) {
throw new LogicException(\sprintf('The "%s" attribute has %d configurators. Use "getAttributeAutoconfigurators()" to get all of them.', $attribute, count($configurators)));
}

$autoconfiguredAttributes[$attribute] = $configurators[0];
}

return $autoconfiguredAttributes;
}

/**
* @return array<class-string, callable[]>
*/
public function getAttributeAutoconfigurators(): array
{
return $this->autoconfiguredAttributes;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\Attribute\AsTaggedItem;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
Expand All @@ -34,6 +35,7 @@
use Symfony\Component\DependencyInjection\Exception\BadMethodCallException;
use Symfony\Component\DependencyInjection\Exception\EnvNotFoundException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
Expand Down Expand Up @@ -829,6 +831,36 @@ public function testMergeThrowsExceptionForDuplicateAutomaticInstanceofDefinitio
$container->merge($config);
}

public function testMergeAttributeAutoconfiguration()
{
$container = new ContainerBuilder();
$container->registerAttributeForAutoconfiguration(AsTaggedItem::class, $c1 = static function (Definition $definition) {});
$config = new ContainerBuilder();
$config->registerAttributeForAutoconfiguration(AsTaggedItem::class, $c2 = function (Definition $definition) {});

$container->merge($config);
$this->assertSame([AsTaggedItem::class => [$c1, $c2]], $container->getAttributeAutoconfigurators());
}

/**
* @group legacy
*/
public function testGetAutoconfiguredAttributes()
{
$container = new ContainerBuilder();
$container->registerAttributeForAutoconfiguration(AsTaggedItem::class, $c = static function () {});

$this->expectUserDeprecationMessage('Since symfony/dependency-injection 7.3: The "Symfony\Component\DependencyInjection\ContainerBuilder::getAutoconfiguredAttributes()" method is deprecated, use "getAttributeAutoconfigurators()" instead.');
$configurators = $container->getAutoconfiguredAttributes();
$this->assertSame($c, $configurators[AsTaggedItem::class]);

// Method call fails with more than one configurator for a given attribute
$container->registerAttributeForAutoconfiguration(AsTaggedItem::class, $c = static function () {});

$this->expectException(LogicException::class);
$container->getAutoconfiguredAttributes();
}

public function testResolveEnvValues()
{
$_ENV['DUMMY_ENV_VAR'] = 'du%%y';
Expand Down
Loading