minor #22648 Improving autowire exception when you type-hint a class & alias is available (weaverryan)

This PR was merged into the 3.3-dev branch.

Discussion
----------

Improving autowire exception when you type-hint a class & alias is available

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | none
| License       | MIT
| Doc PR        | n/a

Suppose you type-hint a class instead of the correct interface (which is aliased):

```php
public function __construct(Logger $logger)
```

Current error:

> Cannot autowire service "AppBundle\Security\PostVoter": argument "$logger" of method "__construct()" references class "Symfony\Bridge\Monolog\Logger" but no such service exists. You should maybe alias this class to one of these existing services: "monolog.logger", "monolog.logger.request", "monolog.logger.console", "monolog.logger.cache", "monolog.logger.templating", "monolog.logger.translation", "monolog.logger.profiler", "monolog.logger.php", "monolog.logger.event", "monolog.logger.router", "monolog.logger.security", "monolog.logger.doctrine"; or type-hint against interface "Psr\Log\LoggerInterface" instead.

New error:

> Cannot autowire service "AppBundle\Security\PostVoter": argument "$logger" of method "__construct()" references class "Symfony\Bridge\Monolog\Logger" but no such service exists. Try changing the type-hint to "Psr\Log\LoggerInterface" instead.

The correct "suggestion" was always  there (at the end). I think if there is already a definitive alias available for your type-hint, we can say that they are simply using the wrong type-hint and suggest *only* that.

Commits
-------

5a3c156798 Improving autowire exception when you type-hint a class and there is an interface alias available
This commit is contained in:
Fabien Potencier 2017-05-05 08:45:54 -07:00
commit e5bb8fad3f
2 changed files with 63 additions and 21 deletions

View File

@ -445,7 +445,28 @@ class AutowirePass extends AbstractRecursivePass
private function createTypeAlternatives(TypedReference $reference)
{
if (isset($this->ambiguousServiceTypes[$type = $reference->getType()])) {
$type = $reference->getType();
$aliases = array();
foreach (class_parents($type) + class_implements($type) as $parent) {
if ($this->container->has($parent) && !$this->container->findDefinition($parent)->isAbstract()) {
$aliases[] = $parent;
}
}
if (1 < $len = count($aliases)) {
$message = ' Try changing the type-hint to one of its parents: ';
for ($i = 0, --$len; $i < $len; ++$i) {
$message .= sprintf('%s "%s", ', class_exists($aliases[$i], false) ? 'class' : 'interface', $aliases[$i]);
}
$message .= sprintf('or %s "%s".', class_exists($aliases[$i], false) ? 'class' : 'interface', $aliases[$i]);
return $message;
}
if ($aliases) {
return sprintf(' Try changing the type-hint to "%s" instead.', $aliases[0]);
}
if (isset($this->ambiguousServiceTypes[$type])) {
$message = sprintf('one of these existing services: "%s"', implode('", "', $this->ambiguousServiceTypes[$type]));
} elseif (isset($this->types[$type])) {
$message = sprintf('the existing "%s" service', $this->types[$type]);
@ -454,26 +475,8 @@ class AutowirePass extends AbstractRecursivePass
} else {
return;
}
$message = sprintf(' You should maybe alias this %s to %s', class_exists($type, false) ? 'class' : 'interface', $message);
$aliases = array();
foreach (class_parents($type) + class_implements($type) as $parent) {
if ($this->container->has($parent) && !$this->container->findDefinition($parent)->isAbstract()) {
$aliases[] = $parent;
}
}
if (1 < $len = count($aliases)) {
$message .= '; or type-hint against one of its parents: ';
for ($i = 0, --$len; $i < $len; ++$i) {
$message .= sprintf('%s "%s", ', class_exists($aliases[$i], false) ? 'class' : 'interface', $aliases[$i]);
}
$message .= sprintf('or %s "%s"', class_exists($aliases[$i], false) ? 'class' : 'interface', $aliases[$i]);
} elseif ($aliases) {
$message .= sprintf('; or type-hint against %s "%s" instead', class_exists($aliases[0], false) ? 'class' : 'interface', $aliases[0]);
}
return $message.'.';
return sprintf(' You should maybe alias this %s to %s.', class_exists($type, false) ? 'class' : 'interface', $message);
}
/**

View File

@ -703,7 +703,7 @@ class AutowirePassTest extends TestCase
* @group legacy
* @expectedDeprecation Autowiring services based on the types they implement is deprecated since Symfony 3.3 and won't be supported in version 4.0. You should rename (or alias) the "i" service to "Symfony\Component\DependencyInjection\Tests\Compiler\I" instead.
* @expectedExceptionInSymfony4 \Symfony\Component\DependencyInjection\Exception\RuntimeException
* @expectedExceptionMessageInSymfony4 Cannot autowire service "j": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\J::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\I" but no such service exists. You should maybe alias this class to the existing "i" service; or type-hint against interface "Symfony\Component\DependencyInjection\Tests\Compiler\IInterface" instead.
* @expectedExceptionMessageInSymfony4 Cannot autowire service "j": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\J::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\I" but no such service exists. Try changing the type-hint to "Symfony\Component\DependencyInjection\Tests\Compiler\IInterface" instead.
*/
public function testByIdAlternative()
{
@ -717,6 +717,45 @@ class AutowirePassTest extends TestCase
$pass = new AutowirePass();
$pass->process($container);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
* @expectedExceptionMessage Cannot autowire service "j": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\J::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\I" but no such service exists. Try changing the type-hint to "Symfony\Component\DependencyInjection\Tests\Compiler\IInterface" instead.
*/
public function testExceptionWhenAliasExists()
{
$container = new ContainerBuilder();
// multiple I services... but there *is* IInterface available
$container->setAlias(IInterface::class, 'i');
$container->register('i', I::class);
$container->register('i2', I::class);
// J type-hints against I concretely
$container->register('j', J::class)
->setAutowired(true);
$pass = new AutowirePass();
$pass->process($container);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
* @expectedExceptionMessage Cannot autowire service "j": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\J::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\I" but no such service exists. You should maybe alias this class to one of these existing services: "i", "i2".
*/
public function testExceptionWhenAliasDoesNotExist()
{
$container = new ContainerBuilder();
// multiple I instances... but no IInterface alias
$container->register('i', I::class);
$container->register('i2', I::class);
// J type-hints against I concretely
$container->register('j', J::class)
->setAutowired(true);
$pass = new AutowirePass();
$pass->process($container);
}
}
class Foo