Skip to content

Commit 9665e30

Browse files
[DependencyInjection] Improve autowiring errors when named autowiring aliases exist
1 parent cef4169 commit 9665e30

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Compiler/AutowirePass.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ class AutowirePass extends AbstractRecursivePass
3333
{
3434
private $types;
3535
private $ambiguousServiceTypes;
36+
private $autowiringAliases;
3637
private $lastFailure;
3738
private $throwOnAutowiringException;
3839
private $decoratedClass;
@@ -343,10 +344,15 @@ private function populateAvailableTypes(ContainerBuilder $container)
343344
{
344345
$this->types = [];
345346
$this->ambiguousServiceTypes = [];
347+
$this->autowiringAliases = [];
346348

347349
foreach ($container->getDefinitions() as $id => $definition) {
348350
$this->populateAvailableType($container, $id, $definition);
349351
}
352+
353+
foreach ($container->getAliases() as $id => $alias) {
354+
$this->populateAutowiringAlias($id);
355+
}
350356
}
351357

352358
/**
@@ -370,6 +376,8 @@ private function populateAvailableType(ContainerBuilder $container, string $id,
370376
do {
371377
$this->set($reflectionClass->name, $id);
372378
} while ($reflectionClass = $reflectionClass->getParentClass());
379+
380+
$this->populateAutowiringAlias($id);
373381
}
374382

375383
/**
@@ -459,6 +467,10 @@ private function createTypeAlternatives(ContainerBuilder $container, TypedRefere
459467
}
460468

461469
$servicesAndAliases = $container->getServiceIds();
470+
if (null !== ($autowiringAliases = $this->autowiringAliases[$type] ?? null) && !isset($autowiringAliases[''])) {
471+
return sprintf(' Available autowiring aliases for this %s are: "$%s".', class_exists($type, false) ? 'class' : 'interface', implode('", "$', $autowiringAliases));
472+
}
473+
462474
if (!$container->has($type) && false !== $key = array_search(strtolower($type), array_map('strtolower', $servicesAndAliases))) {
463475
return sprintf(' Did you mean "%s"?', $servicesAndAliases[$key]);
464476
} elseif (isset($this->ambiguousServiceTypes[$type])) {
@@ -497,4 +509,18 @@ private function getAliasesSuggestionForType(ContainerBuilder $container, string
497509

498510
return null;
499511
}
512+
513+
private function populateAutowiringAlias(string $id): void
514+
{
515+
if (!preg_match('/(?(DEFINE)(?<V>[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+))^((?&V)(?:\\\\(?&V))*+)(?: \$((?&V)))?$/', $id, $m)) {
516+
return;
517+
}
518+
519+
$type = $m[2];
520+
$name = $m[3] ?? '';
521+
522+
if (class_exists($type, false) || interface_exists($type, false)) {
523+
$this->autowiringAliases[$type][$name] = $name;
524+
}
525+
}
500526
}

0 commit comments

Comments
 (0)