-
-
Notifications
You must be signed in to change notification settings - Fork 439
Expand file tree
/
Copy pathParentClassMagicCallGuard.php
More file actions
88 lines (74 loc) · 2.76 KB
/
ParentClassMagicCallGuard.php
File metadata and controls
88 lines (74 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
declare(strict_types=1);
namespace Rector\Privatization\Guard;
use PhpParser\PrettyPrinterAbstract;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt\Class_;
use PhpParser\PrettyPrinter\Standard;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\PhpParser\AstResolver;
use Rector\PhpParser\Node\BetterNodeFinder;
final class ParentClassMagicCallGuard
{
/**
* To speed up analysis
* @var string[]
*/
private const KNOWN_DYNAMIC_CALL_CLASSES = [Standard::class, PrettyPrinterAbstract::class];
/**
* @var array<string, bool>
*/
private array $cachedContainsByClassName = [];
public function __construct(
private readonly NodeNameResolver $nodeNameResolver,
private readonly AstResolver $astResolver,
private readonly BetterNodeFinder $betterNodeFinder
) {
foreach (self::KNOWN_DYNAMIC_CALL_CLASSES as $knownDynamicCallClass) {
$this->cachedContainsByClassName[$knownDynamicCallClass] = true;
}
}
/**
* E.g. parent class has $this->{$magicName} call that might call the protected method
* If we make it private, it will break the code
*/
public function containsParentClassMagicCall(Class_ $class): bool
{
if (! $class->extends instanceof Name) {
return false;
}
// cache as heavy AST parsing here
$className = $this->nodeNameResolver->getName($class);
if (isset($this->cachedContainsByClassName[$className])) {
return $this->cachedContainsByClassName[$className];
}
$parentClassName = $this->nodeNameResolver->getName($class->extends);
if (isset($this->cachedContainsByClassName[$parentClassName])) {
return $this->cachedContainsByClassName[$parentClassName];
}
$parentClass = $this->astResolver->resolveClassFromName($parentClassName);
if (! $parentClass instanceof Class_) {
$this->cachedContainsByClassName[$parentClassName] = false;
return false;
}
foreach ($parentClass->getMethods() as $classMethod) {
if ($classMethod->isAbstract()) {
continue;
}
/** @var MethodCall[] $methodCalls */
$methodCalls = $this->betterNodeFinder->findInstancesOfScoped(
(array) $classMethod->stmts,
MethodCall::class
);
foreach ($methodCalls as $methodCall) {
if ($methodCall->name instanceof Expr) {
$this->cachedContainsByClassName[$parentClassName] = true;
return true;
}
}
}
return $this->containsParentClassMagicCall($parentClass);
}
}