-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCallToPrivateMethodRule.php
106 lines (86 loc) · 2.58 KB
/
CallToPrivateMethodRule.php
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php declare(strict_types = 1);
namespace Swissspidy\PHPStan\Rules\NoPrivate;
use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Identifier;
use PHPStan\Analyser\Scope;
use PHPStan\Broker\ClassNotFoundException;
use PHPStan\Reflection\MissingMethodFromReflectionException;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\FileTypeMapper;
use function sprintf;
/**
* @implements Rule<MethodCall>
*/
class CallToPrivateMethodRule implements Rule
{
/** @var ReflectionProvider */
private $reflectionProvider;
/** @var FileTypeMapper */
private $fileTypeMapper;
public function __construct(ReflectionProvider $reflectionProvider, FileTypeMapper $fileTypeMapper)
{
$this->reflectionProvider = $reflectionProvider;
$this->fileTypeMapper = $fileTypeMapper;
}
public function getNodeType(): string
{
return MethodCall::class;
}
public function processNode(Node $node, Scope $scope): array
{
if (!$node->name instanceof Identifier) {
return [];
}
$methodName = $node->name->name;
$methodCalledOnType = $scope->getType($node->var);
$referencedClasses = $methodCalledOnType->getObjectClassNames();
foreach ($referencedClasses as $referencedClass) {
try {
$classReflection = $this->reflectionProvider->getClass($referencedClass);
$methodReflection = $classReflection->getMethod($methodName, $scope);
if ($methodReflection->isPrivate()) {
continue;
}
$docComment = $methodReflection->getDocComment();
if ($docComment === null) {
continue;
}
$resolvedPhpDoc = $this->fileTypeMapper->getResolvedPhpDoc(
$methodReflection->getDeclaringClass()->getFileName(),
$classReflection->getName(),
null,
$methodReflection->getName(),
$docComment
);
if (!PrivateAnnotationHelper::isPrivate($resolvedPhpDoc)) {
continue;
}
if (
$scope->isInClass() &&
$classReflection->getName() === $methodReflection->getDeclaringClass()->getName()
) {
continue;
}
return [
RuleErrorBuilder::message(
sprintf(
'Call to private/internal method %s() of class %s.',
$methodReflection->getName(),
$methodReflection->getDeclaringClass()->getName()
)
)
->identifier('no.private.method')
->build()
];
} catch (ClassNotFoundException $e) {
// Other rules will notify if the class is not found
} catch (MissingMethodFromReflectionException $e) {
// Other rules will notify if the the method is not found
}
}
return [];
}
}