diff --git a/rules-tests/CodeQuality/Rector/Class_/ControllerMethodInjectionToConstructorRector/Fixture/different_parameter_type_same_name_used.php.inc b/rules-tests/CodeQuality/Rector/Class_/ControllerMethodInjectionToConstructorRector/Fixture/different_parameter_type_same_name_used.php.inc new file mode 100644 index 00000000..0c7b84db --- /dev/null +++ b/rules-tests/CodeQuality/Rector/Class_/ControllerMethodInjectionToConstructorRector/Fixture/different_parameter_type_same_name_used.php.inc @@ -0,0 +1,58 @@ + +----- +service); + } + + public function two() + { + dump($this->service); + } + + public function three(Bar $service) + { + dump($service); + } +} + +?> \ No newline at end of file diff --git a/rules/CodeQuality/Rector/Class_/ControllerMethodInjectionToConstructorRector.php b/rules/CodeQuality/Rector/Class_/ControllerMethodInjectionToConstructorRector.php index 27338244..23f6a317 100644 --- a/rules/CodeQuality/Rector/Class_/ControllerMethodInjectionToConstructorRector.php +++ b/rules/CodeQuality/Rector/Class_/ControllerMethodInjectionToConstructorRector.php @@ -131,6 +131,12 @@ public function refactor(Node $node): ?Node } } + /** @var array $paramsToRemove */ + $paramsToRemove = []; + + /** @var array $methodParamNamesToReplace */ + $methodParamNamesToReplace = []; + foreach ($node->getMethods() as $classMethod) { if ($this->shouldSkipClassMethod($classMethod)) { continue; @@ -213,8 +219,10 @@ public function refactor(Node $node): ?Node continue; } - unset($classMethod->params[$key]); - $propertyMetadatas[] = new PropertyMetadata($this->getName($param->var), $paramType); + $paramName = $this->getName($param->var); + $paramsToRemove[] = [$classMethod, $key]; + $propertyMetadatas[$paramName] = new PropertyMetadata($paramName, $paramType); + $methodParamNamesToReplace[$classMethod->name->toString()][] = $paramName; } } @@ -223,9 +231,9 @@ public function refactor(Node $node): ?Node return null; } - $paramNamesToReplace = []; - foreach ($propertyMetadatas as $propertyMetadata) { - $paramNamesToReplace[] = $propertyMetadata->getName(); + // defer param removal to after collection to avoid mutation during iteration + foreach ($paramsToRemove as [$methodToModify, $paramKey]) { + unset($methodToModify->params[$paramKey]); } // 1. update constructor @@ -238,7 +246,12 @@ public function refactor(Node $node): ?Node continue; } - $this->replaceParamUseWithPropertyFetch($classMethod, $paramNamesToReplace); + $methodName = $classMethod->name->toString(); + if (! isset($methodParamNamesToReplace[$methodName])) { + continue; + } + + $this->replaceParamUseWithPropertyFetch($classMethod, $methodParamNamesToReplace[$methodName]); } return $node;