Skip to content

Commit

Permalink
[Performance][DeadCode] Early check has private methods before find()…
Browse files Browse the repository at this point in the history
… on dynamic call checks on RemoveUnusedPrivateMethodRector (#5687)

* [Performance][DeadCode] Early check has private methods on RemoveUnusedPrivateMethodRector

* clean up comments
  • Loading branch information
samsonasik committed Mar 4, 2024
1 parent b4212ed commit 7df4894
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
@@ -0,0 +1,15 @@
<?php

namespace Rector\Tests\DeadCode\Rector\ClassMethod\RemoveUnusedPrivateMethodRector\Fixture;

class SkipAllMethodsPublic
{
public function run()
{
}

public function run2()
{
}
}
?>
Expand Up @@ -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;
}

Expand Down Expand Up @@ -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;
}
Expand All @@ -130,7 +137,6 @@ private function shouldSkip(ClassMethod $classMethod, ?ClassReflection $classRef
return true;
}

// skips interfaces by default too
if (! $classMethod->isPrivate()) {
return true;
}
Expand All @@ -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 {
Expand Down

0 comments on commit 7df4894

Please sign in to comment.