Skip to content

Commit

Permalink
minor #22648 Improving autowire exception when you type-hint a class …
Browse files Browse the repository at this point in the history
…& 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
-------

5a3c156 Improving autowire exception when you type-hint a class and there is an interface alias available
  • Loading branch information
fabpot committed May 5, 2017
2 parents fb02140 + 5a3c156 commit e5bb8fa
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 17 deletions.
35 changes: 19 additions & 16 deletions src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php
Expand Up @@ -445,35 +445,38 @@ private function createTypeNotFoundMessage(TypedReference $reference, $label)

private function createTypeAlternatives(TypedReference $reference)
{
if (isset($this->ambiguousServiceTypes[$type = $reference->getType()])) {
$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]);
} elseif ($reference->getRequiringClass() && !$reference->canBeAutoregistered()) {
return ' It cannot be auto-registered because it is from a different root namespace.';
} else {
return;
}
$message = sprintf(' You should maybe alias this %s to %s', class_exists($type, false) ? 'class' : 'interface', $message);
$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 .= '; or type-hint against one of its parents: ';
$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]);
} elseif ($aliases) {
$message .= sprintf('; or type-hint against %s "%s" instead', class_exists($aliases[0], false) ? 'class' : 'interface', $aliases[0]);
$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]);
} elseif ($reference->getRequiringClass() && !$reference->canBeAutoregistered()) {
return ' It cannot be auto-registered because it is from a different root namespace.';
} else {
return;
}

return $message.'.';
return sprintf(' You should maybe alias this %s to %s.', class_exists($type, false) ? 'class' : 'interface', $message);
}

/**
Expand Down
Expand Up @@ -703,7 +703,7 @@ public function provideNotWireableCalls()
* @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()
{
Expand All @@ -717,6 +717,45 @@ public function testByIdAlternative()
$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
Expand Down

0 comments on commit e5bb8fa

Please sign in to comment.