bug #22999 Better DI type deprecation message (weaverryan)

This PR was merged into the 3.3 branch.

Discussion
----------

Better DI type deprecation message

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

This is the most common autowiring deprecation:

```php
public function __construct(UserPasswordEncoder $encoder)
```

You *should* type-hint `UserPasswordEncoderInterface`

Current deprecation message:
> 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 "security.user_password_encoder.generic" service to "Symfony\Component\Security\Core\Encoder\UserPasswordEncoder" instead.

Updated message:
> Autowiring services based on the types they implement is deprecated since Symfony 3.3 and won't be supported in version 4.0. Try changing the type-hint for argument "$encoder" of method "AppBundle\Service\TestServiceSubscriber::__construct()" to "Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface" instead.

This only happens if we detect that there is a service/alias in the container (e.g. `...\UserPasswordEncoderInterface`) for the type-hint (`...\UserPasswordEncoder)`. Otherwise, if there is no correct type-hint in the container, we give the old recommendation (about aliasing).

The only complex case (of giving good directions on *where* to fix things) is with a class that implements `ServiceSubscriberInterface` (where the type-hint is in the `getSusbcribedServices()` method). In that case, the notice is:

> Autowiring services based on the types they implement is deprecated since Symfony 3.3 and won't be supported in version 4.0. Try changing the type-hint for "Symfony\Component\Security\Core\Encoder\UserPasswordEncoder" in "AppBundle\Service\TestServiceSubscriber" to "Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface" instead.

Commits
-------

a990d5c558 Improving deprecation message when hitting the "deprecated type" lookup, but an alias is available
This commit is contained in:
Fabien Potencier 2017-05-31 11:14:35 -07:00
commit 5e40e19081
2 changed files with 86 additions and 25 deletions

View File

@ -114,7 +114,7 @@ class AutowirePass extends AbstractRecursivePass
private function doProcessValue($value, $isRoot = false)
{
if ($value instanceof TypedReference) {
if ($ref = $this->getAutowiredReference($value)) {
if ($ref = $this->getAutowiredReference($value, $value->getRequiringClass() ? sprintf('for "%s" in "%s"', $value->getType(), $value->getRequiringClass()) : '')) {
return $ref;
}
$this->container->log($this, $this->createTypeNotFoundMessage($value, 'it'));
@ -282,7 +282,7 @@ class AutowirePass extends AbstractRecursivePass
continue;
}
if (!$value = $this->getAutowiredReference($ref = new TypedReference($type, $type, !$parameter->isOptional() ? $class : ''))) {
if (!$value = $this->getAutowiredReference($ref = new TypedReference($type, $type, !$parameter->isOptional() ? $class : ''), 'for '.sprintf('argument "$%s" of method "%s()"', $parameter->name, $class.'::'.$method))) {
$failureMessage = $this->createTypeNotFoundMessage($ref, sprintf('argument "$%s" of method "%s()"', $parameter->name, $class !== $this->currentId ? $class.'::'.$method : $method));
if ($parameter->isDefaultValueAvailable()) {
@ -316,7 +316,7 @@ class AutowirePass extends AbstractRecursivePass
/**
* @return TypedReference|null A reference to the service matching the given type, if any
*/
private function getAutowiredReference(TypedReference $reference)
private function getAutowiredReference(TypedReference $reference, $deprecationMessage)
{
$this->lastFailure = null;
$type = $reference->getType();
@ -334,7 +334,14 @@ class AutowirePass extends AbstractRecursivePass
}
if (isset($this->types[$type])) {
@trigger_error(sprintf('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 %s the "%s" service to "%s" instead.', isset($this->types[$this->types[$type]]) ? 'alias' : 'rename (or alias)', $this->types[$type], $type), E_USER_DEPRECATED);
$message = 'Autowiring services based on the types they implement is deprecated since Symfony 3.3 and won\'t be supported in version 4.0.';
if ($aliasSuggestion = $this->getAliasesSuggestionForType($type = $reference->getType(), $deprecationMessage)) {
$message .= ' '.$aliasSuggestion;
} else {
$message .= sprintf(' You should %s the "%s" service to "%s" instead.', isset($this->types[$this->types[$type]]) ? 'alias' : 'rename (or alias)', $this->types[$type], $type);
}
@trigger_error($message, E_USER_DEPRECATED);
return new TypedReference($this->types[$type], $type);
}
@ -490,25 +497,9 @@ class AutowirePass extends AbstractRecursivePass
private function createTypeAlternatives(TypedReference $reference)
{
$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]);
// try suggesting available aliases first
if ($message = $this->getAliasesSuggestionForType($type = $reference->getType())) {
return ' '.$message;
}
if (isset($this->ambiguousServiceTypes[$type])) {
@ -548,4 +539,29 @@ class AutowirePass extends AbstractRecursivePass
return $methodArgumentsMetadata;
}
private function getAliasesSuggestionForType($type, $extraContext = null)
{
$aliases = array();
foreach (class_parents($type) + class_implements($type) as $parent) {
if ($this->container->has($parent) && !$this->container->findDefinition($parent)->isAbstract()) {
$aliases[] = $parent;
}
}
$extraContext = $extraContext ? ' '.$extraContext : '';
if (1 < $len = count($aliases)) {
$message = sprintf('Try changing the type-hint%s to one of its parents: ', $extraContext);
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%s to "%s" instead.', $extraContext, $aliases[0]);
}
}
}

View File

@ -78,6 +78,28 @@ class AutowirePassTest extends TestCase
$this->assertEquals(B::class, (string) $container->getDefinition('c')->getArgument(0));
}
/**
* @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. Try changing the type-hint for argument "$a" of method "Symfony\Component\DependencyInjection\Tests\Compiler\C::__construct()" to "Symfony\Component\DependencyInjection\Tests\Compiler\AInterface" instead.
* @expectedExceptionInSymfony4 \Symfony\Component\DependencyInjection\Exception\RuntimeException
* @expectedExceptionMessageInSymfony4 Cannot autowire service "c": argument "$a" of method "Symfony\Component\DependencyInjection\Tests\Compiler\C::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\A" but no such service exists. You should maybe alias this class to the existing "Symfony\Component\DependencyInjection\Tests\Compiler\B" service.
*/
public function testProcessLegacyAutowireWithAvailableInterface()
{
$container = new ContainerBuilder();
$container->setAlias(AInterface::class, B::class);
$container->register(B::class);
$cDefinition = $container->register('c', __NAMESPACE__.'\C');
$cDefinition->setAutowired(true);
(new ResolveClassPass())->process($container);
(new AutowirePass())->process($container);
$this->assertCount(1, $container->getDefinition('c')->getArguments());
$this->assertEquals(B::class, (string) $container->getDefinition('c')->getArgument(0));
}
/**
* @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 alias the "Symfony\Component\DependencyInjection\Tests\Compiler\F" service to "Symfony\Component\DependencyInjection\Tests\Compiler\DInterface" instead.
@ -730,7 +752,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.
* @expectedDeprecation Autowiring services based on the types they implement is deprecated since Symfony 3.3 and won't be supported in version 4.0. Try changing the type-hint for argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\J::__construct()" to "Symfony\Component\DependencyInjection\Tests\Compiler\IInterface" instead.
* @expectedExceptionInSymfony4 \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException
* @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.
*/
@ -747,6 +769,25 @@ class AutowirePassTest extends TestCase
$pass->process($container);
}
/**
* @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. Try changing the type-hint for "Symfony\Component\DependencyInjection\Tests\Compiler\A" in "Symfony\Component\DependencyInjection\Tests\Compiler\Bar" to "Symfony\Component\DependencyInjection\Tests\Compiler\AInterface" instead.
*/
public function testTypedReferenceDeprecationNotice()
{
$container = new ContainerBuilder();
$container->register('aClass', A::class);
$container->setAlias(AInterface::class, 'aClass');
$container
->register('bar', Bar::class)
->setProperty('a', array(new TypedReference(A::class, A::class, Bar::class)))
;
$pass = new AutowirePass();
$pass->process($container);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException
* @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.
@ -798,7 +839,11 @@ class Bar
}
}
class A
interface AInterface
{
}
class A implements AInterface
{
public static function create(Foo $foo)
{