Skip to content

Commit

Permalink
bug #22999 Better DI type deprecation message (weaverryan)
Browse files Browse the repository at this point in the history
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
-------

a990d5c Improving deprecation message when hitting the "deprecated type" lookup, but an alias is available
  • Loading branch information
fabpot committed May 31, 2017
2 parents b136719 + a990d5c commit 5e40e19
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 25 deletions.
62 changes: 39 additions & 23 deletions src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php
Expand Up @@ -114,7 +114,7 @@ protected function processValue($value, $isRoot = false)
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'));
Expand Down Expand Up @@ -282,7 +282,7 @@ private function autowireMethod(\ReflectionFunctionAbstract $reflectionMethod, a
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()) {
Expand Down Expand Up @@ -316,7 +316,7 @@ private function autowireMethod(\ReflectionFunctionAbstract $reflectionMethod, a
/**
* @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();
Expand All @@ -334,7 +334,14 @@ private function getAutowiredReference(TypedReference $reference)
}

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);
}
Expand Down Expand Up @@ -490,25 +497,9 @@ private function createTypeNotFoundMessage(TypedReference $reference, $label)

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])) {
Expand Down Expand Up @@ -548,4 +539,29 @@ private static function getResourceMetadataForMethod(\ReflectionMethod $method)

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]);
}
}
}
Expand Up @@ -78,6 +78,28 @@ public function testProcessAutowireParent()
$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.
Expand Down Expand Up @@ -730,7 +752,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.
* @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.
*/
Expand All @@ -747,6 +769,25 @@ public function testByIdAlternative()
$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.
Expand Down Expand Up @@ -798,7 +839,11 @@ public function __construct(Foo $foo)
}
}

class A
interface AInterface
{
}

class A implements AInterface
{
public static function create(Foo $foo)
{
Expand Down

0 comments on commit 5e40e19

Please sign in to comment.