Skip to content

Commit 36488ed

Browse files
authored
[CodeQuality] Skip different service same name on ControllerMethodInjectionToConstructorRector (#894)
* [CodeQuality] Skip different service same name on ControllerMethodInjectionToConstructorRector * Fix * Fix
1 parent bd79952 commit 36488ed

2 files changed

Lines changed: 45 additions & 4 deletions

File tree

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Rector\Symfony\Tests\CodeQuality\Rector\Class_\ControllerMethodInjectionToConstructorRector\Fixture;
6+
7+
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
8+
9+
final class DemoController extends AbstractController
10+
{
11+
public function __construct(
12+
private readonly UpdateAppContext $context // This is not the same service as AdminContext
13+
) {
14+
}
15+
16+
public function __invoke(AdminContext $context): int
17+
{
18+
return $context->getNumber(); // This is not the same service as UpdateAppContext
19+
}
20+
}

rules/CodeQuality/Rector/Class_/ControllerMethodInjectionToConstructorRector.php

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,16 @@ public function refactor(Node $node): ?Node
118118

119119
$propertyMetadatas = [];
120120

121+
$constructParamVariables = [];
122+
$constructClassMethod = $node->getMethod(MethodName::CONSTRUCT);
123+
if ($constructClassMethod instanceof ClassMethod) {
124+
foreach ($constructClassMethod->params as $param) {
125+
if ($param->type instanceof FullyQualified) {
126+
$constructParamVariables[$param->type->toString()] = $this->getName($param->var);
127+
}
128+
}
129+
}
130+
121131
foreach ($node->getMethods() as $classMethod) {
122132
if ($this->shouldSkipClassMethod($classMethod)) {
123133
continue;
@@ -152,10 +162,21 @@ public function refactor(Node $node): ?Node
152162

153163
$paramType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type);
154164

155-
if ($paramType instanceof ObjectType) {
156-
if ($paramType->isEnum()->yes()) {
157-
continue;
158-
}
165+
if (! $paramType instanceof ObjectType) {
166+
continue;
167+
}
168+
169+
if ($paramType->isEnum()->yes()) {
170+
continue;
171+
}
172+
173+
if (
174+
$constructParamVariables !== []
175+
&& in_array($this->getName($param->var), $constructParamVariables, true)
176+
&&
177+
! in_array($this->getName($param->type), array_keys($constructParamVariables), true)
178+
) {
179+
continue;
159180
}
160181

161182
unset($classMethod->params[$key]);

0 commit comments

Comments
 (0)