Skip to content

[DependencyInjection] autowire union and intersection types #43479

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
Oct 13, 2021
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 @@ -7,6 +7,7 @@ CHANGELOG
* Add `service_closure()` to the PHP-DSL
* Add support for autoconfigurable attributes on methods, properties and parameters
* Make auto-aliases private by default
* Add support for autowiring union and intersection types

5.3
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ class AutowirePass extends AbstractRecursivePass
private $decoratedMethodIndex;
private $decoratedMethodArgumentIndex;
private $typesClone;
private $combinedAliases;

public function __construct(bool $throwOnAutowireException = true)
{
Expand All @@ -60,6 +61,8 @@ public function __construct(bool $throwOnAutowireException = true)
*/
public function process(ContainerBuilder $container)
{
$this->populateCombinedAliases($container);

try {
$this->typesClone = clone $this;
parent::process($container);
Expand All @@ -72,6 +75,7 @@ public function process(ContainerBuilder $container)
$this->decoratedMethodIndex = null;
$this->decoratedMethodArgumentIndex = null;
$this->typesClone = null;
$this->combinedAliases = [];
}
}

Expand Down Expand Up @@ -223,8 +227,6 @@ private function autowireCalls(\ReflectionClass $reflectionClass, bool $isRoot,
/**
* Autowires the constructor or a method.
*
* @return array
*
* @throws AutowiringFailedException
*/
private function autowireMethod(\ReflectionFunctionAbstract $reflectionMethod, array $arguments, bool $checkAttributes, int $methodIndex): array
Expand Down Expand Up @@ -363,8 +365,12 @@ private function getAutowiredReference(TypedReference $reference): ?TypedReferen
return new TypedReference($alias, $type, $reference->getInvalidBehavior());
}

if (null !== ($alias = $this->combinedAliases[$alias] ?? null) && !$this->container->findDefinition($alias)->isAbstract()) {
return new TypedReference($alias, $type, $reference->getInvalidBehavior());
}

if ($this->container->has($name) && !$this->container->findDefinition($name)->isAbstract()) {
foreach ($this->container->getAliases() as $id => $alias) {
foreach ($this->container->getAliases() + $this->combinedAliases as $id => $alias) {
if ($name === (string) $alias && str_starts_with($id, $type.' $')) {
return new TypedReference($name, $type, $reference->getInvalidBehavior());
}
Expand All @@ -376,6 +382,10 @@ private function getAutowiredReference(TypedReference $reference): ?TypedReferen
return new TypedReference($type, $type, $reference->getInvalidBehavior());
}

if (null !== ($alias = $this->combinedAliases[$type] ?? null) && !$this->container->findDefinition($alias)->isAbstract()) {
return new TypedReference($alias, $type, $reference->getInvalidBehavior());
}

return null;
}

Expand Down Expand Up @@ -565,4 +575,45 @@ private function populateAutowiringAlias(string $id): void
$this->autowiringAliases[$type][$name] = $name;
}
}

private function populateCombinedAliases(ContainerBuilder $container): void
{
$this->combinedAliases = [];
$reverseAliases = [];

foreach ($container->getAliases() as $id => $alias) {
if (!preg_match('/(?(DEFINE)(?<V>[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+))^((?&V)(?:\\\\(?&V))*+)(?: \$((?&V)))?$/', $id, $m)) {
continue;
}

$type = $m[2];
$name = $m[3] ?? '';
$reverseAliases[(string) $alias][$name][] = $type;
}

foreach ($reverseAliases as $alias => $names) {
foreach ($names as $name => $types) {
if (2 > $count = \count($types)) {
continue;
}
sort($types);
$i = 1 << $count;

// compute the powerset of the list of types
while ($i--) {
$set = [];
for ($j = 0; $j < $count; ++$j) {
if ($i & (1 << $j)) {
$set[] = $types[$j];
}
}

if (2 <= \count($set)) {
$this->combinedAliases[implode('&', $set).('' === $name ? '' : ' $'.$name)] = $alias;
$this->combinedAliases[implode('|', $set).('' === $name ? '' : ' $'.$name)] = $alias;
}
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ public static function getTypeHint(\ReflectionFunctionAbstract $r, \ReflectionPa
}
}

sort($types);

return $types ? implode($glue, $types) : null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -258,13 +258,31 @@ public function testTypeNotGuessableUnionType()
$pass->process($container);
}

/**
* @requires PHP 8
*/
public function testGuessableUnionType()
{
$container = new ContainerBuilder();

$container->register('b', \stcClass::class);
$container->setAlias(CollisionA::class.' $collision', 'b');
$container->setAlias(CollisionB::class.' $collision', 'b');

$aDefinition = $container->register('a', UnionClasses::class);
$aDefinition->setAutowired(true);

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

$this->assertSame('b', (string) $aDefinition->getArgument(0));
}

/**
* @requires PHP 8.1
*/
public function testTypeNotGuessableIntersectionType()
{
$this->expectException(AutowiringFailedException::class);
$this->expectExceptionMessage('Cannot autowire service "a": argument "$collision" of method "Symfony\Component\DependencyInjection\Tests\Compiler\IntersectionClasses::__construct()" has type "Symfony\Component\DependencyInjection\Tests\Compiler\CollisionInterface&Symfony\Component\DependencyInjection\Tests\Compiler\AnotherInterface" but this class was not found.');
$container = new ContainerBuilder();

$container->register(CollisionInterface::class);
Expand All @@ -273,8 +291,32 @@ public function testTypeNotGuessableIntersectionType()
$aDefinition = $container->register('a', IntersectionClasses::class);
$aDefinition->setAutowired(true);

$pass = new AutowirePass();

$this->expectException(AutowiringFailedException::class);
$this->expectExceptionMessage('Cannot autowire service "a": argument "$collision" of method "Symfony\Component\DependencyInjection\Tests\Compiler\IntersectionClasses::__construct()" has type "Symfony\Component\DependencyInjection\Tests\Compiler\AnotherInterface&Symfony\Component\DependencyInjection\Tests\Compiler\CollisionInterface" but this class was not found.');
$pass->process($container);
}

/**
* @requires PHP 8.1
*/
public function testGuessableIntersectionType()
{
$container = new ContainerBuilder();

$container->register('b', \stcClass::class);
$container->setAlias(CollisionInterface::class, 'b');
$container->setAlias(AnotherInterface::class, 'b');
$container->setAlias(DummyInterface::class, 'b');

$aDefinition = $container->register('a', IntersectionClasses::class);
$aDefinition->setAutowired(true);

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

$this->assertSame('b', (string) $aDefinition->getArgument(0));
}

public function testTypeNotGuessableWithTypeSet()
Expand Down Expand Up @@ -516,7 +558,7 @@ public function testScalarArgsCannotBeAutowired()
public function testUnionScalarArgsCannotBeAutowired()
{
$this->expectException(AutowiringFailedException::class);
$this->expectExceptionMessage('Cannot autowire service "union_scalars": argument "$timeout" of method "Symfony\Component\DependencyInjection\Tests\Compiler\UnionScalars::__construct()" is type-hinted "int|float", you should configure its value explicitly.');
$this->expectExceptionMessage('Cannot autowire service "union_scalars": argument "$timeout" of method "Symfony\Component\DependencyInjection\Tests\Compiler\UnionScalars::__construct()" is type-hinted "float|int", you should configure its value explicitly.');
$container = new ContainerBuilder();

$container->register('union_scalars', UnionScalars::class)
Expand Down