diff --git a/rules-tests/DeadCode/Rector/ClassMethod/RemoveUnusedPrivateMethodRector/Fixture/skip_all_methods_public.php.inc b/rules-tests/DeadCode/Rector/ClassMethod/RemoveUnusedPrivateMethodRector/Fixture/skip_all_methods_public.php.inc new file mode 100644 index 00000000000..f8dc6b027ae --- /dev/null +++ b/rules-tests/DeadCode/Rector/ClassMethod/RemoveUnusedPrivateMethodRector/Fixture/skip_all_methods_public.php.inc @@ -0,0 +1,15 @@ + diff --git a/rules/DeadCode/Rector/ClassMethod/RemoveUnusedPrivateMethodRector.php b/rules/DeadCode/Rector/ClassMethod/RemoveUnusedPrivateMethodRector.php index 7c6624f813d..c424bb3c581 100644 --- a/rules/DeadCode/Rector/ClassMethod/RemoveUnusedPrivateMethodRector.php +++ b/rules/DeadCode/Rector/ClassMethod/RemoveUnusedPrivateMethodRector.php @@ -76,11 +76,18 @@ public function getNodeTypes(): array */ public function refactorWithScope(Node $node, Scope $scope): ?Node { - if ($this->hasDynamicMethodCallOnFetchThis($node)) { + $classMethods = $node->getMethods(); + + if ($classMethods === []) { + return null; + } + + $filter = static fn (ClassMethod $classMethod): bool => $classMethod->isPrivate(); + if (array_filter($classMethods, $filter) === []) { return null; } - if ($node->getMethods() === []) { + if ($this->hasDynamicMethodCallOnFetchThis($classMethods)) { return null; } @@ -117,7 +124,7 @@ private function shouldSkip(ClassMethod $classMethod, ?ClassReflection $classRef return true; } - // unreliable to detect trait, interface doesn't make sense + // unreliable to detect trait, interface, anonymous class: doesn't make sense if ($classReflection->isTrait()) { return true; } @@ -130,7 +137,6 @@ private function shouldSkip(ClassMethod $classMethod, ?ClassReflection $classRef return true; } - // skips interfaces by default too if (! $classMethod->isPrivate()) { return true; } @@ -143,9 +149,12 @@ private function shouldSkip(ClassMethod $classMethod, ?ClassReflection $classRef return $classReflection->hasMethod(MethodName::CALL); } - private function hasDynamicMethodCallOnFetchThis(Class_ $class): bool + /** + * @param ClassMethod[] $classMethods + */ + private function hasDynamicMethodCallOnFetchThis(array $classMethods): bool { - foreach ($class->getMethods() as $classMethod) { + foreach ($classMethods as $classMethod) { $isFound = (bool) $this->betterNodeFinder->findFirst( (array) $classMethod->getStmts(), function (Node $subNode): bool {