-
Notifications
You must be signed in to change notification settings - Fork 0
/
StrictVisibility.php
88 lines (78 loc) · 2.84 KB
/
StrictVisibility.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
<?php
declare(strict_types=1);
namespace Orklah\PsalmStrictVisibility\Hooks;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Identifier;
use Psalm\Codebase;
use Psalm\CodeLocation;
use Psalm\Context;
use Psalm\FileManipulation;
use Psalm\Internal\Analyzer\ClassLikeAnalyzer;
use Psalm\Internal\MethodIdentifier;
use Psalm\Issue\PluginIssue;
use Psalm\IssueBuffer;
use Psalm\Plugin\Hook\AfterMethodCallAnalysisInterface;
use Psalm\StatementsSource;
use Psalm\Type\Union;
/**
* Prevents calling private or protected method via proxy
*/
class StrictVisibility implements AfterMethodCallAnalysisInterface
{
/**
* @param MethodCall|StaticCall $expr
* @param FileManipulation[] $file_replacements
*/
public static function afterMethodCallAnalysis(
Expr $expr,
string $method_id,
string $appearing_method_id,
string $declaring_method_id,
Context $context,
StatementsSource $statements_source,
Codebase $codebase,
array &$file_replacements = [],
Union &$return_type_candidate = null
) : void {
if (!$expr instanceof MethodCall) {
return;
}
if (!$expr->name instanceof Identifier) {
return;
}
try {
$method_id = new MethodIdentifier(...explode('::', $declaring_method_id));
$method_storage = $codebase->methods->getStorage($method_id);
$is_private = $method_storage->visibility === ClassLikeAnalyzer::VISIBILITY_PRIVATE;
$is_protected = $method_storage->visibility === ClassLikeAnalyzer::VISIBILITY_PROTECTED;
if ($is_private || $is_protected) {
//method is private or protected, check if the call was made on $this
if ($expr->var instanceof Variable && $expr->var->name !== 'this') {
if ($is_private) {
$issue = new PrivateStrictVisibility(
'Calling private method ' . $method_storage->cased_name . ' via proxy',
new CodeLocation($statements_source, $expr->name)
);
} else {
$issue = new ProtectedStrictVisibility(
'Calling protected method ' . $method_storage->cased_name . ' via proxy',
new CodeLocation($statements_source, $expr->name)
);
}
IssueBuffer::accepts($issue, $statements_source->getSuppressedIssues());
}
}
} catch (\Exception $e) {
// can throw if storage is missing
}
}
}
class ProtectedStrictVisibility extends PluginIssue
{
}
class PrivateStrictVisibility extends PluginIssue
{
}