forked from phpstan/phpstan-src
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTraitContextHelper.php
More file actions
69 lines (59 loc) · 1.67 KB
/
TraitContextHelper.php
File metadata and controls
69 lines (59 loc) · 1.67 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
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Comparison;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Name;
use PHPStan\Analyser\Scope;
use function in_array;
use function is_array;
final class TraitContextHelper
{
/**
* Checks if a comparison expression's result may differ across different
* class contexts when used inside a trait.
*
* Uses a deep traversal to find $this, self::, static::, or parent:: references
* in any sub-expression.
*/
public static function isBinaryOpDependentOnTraitContext(Scope $scope, Expr $left, Expr $right): bool
{
if (!$scope->isInTrait()) {
return false;
}
return self::containsThisDependentExpression($left)
|| self::containsThisDependentExpression($right);
}
private static function containsThisDependentExpression(Expr $expr): bool
{
if ($expr instanceof Expr\Variable) {
return $expr->name === 'this';
}
if (
($expr instanceof Expr\StaticPropertyFetch || $expr instanceof Expr\StaticCall)
&& $expr->class instanceof Name
) {
$className = $expr->class->toString();
if (in_array($className, ['self', 'static', 'parent'], true)) {
return true;
}
}
foreach ($expr->getSubNodeNames() as $name) {
$subNode = $expr->$name;
if ($subNode instanceof Expr) {
if (self::containsThisDependentExpression($subNode)) {
return true;
}
} elseif (is_array($subNode)) {
foreach ($subNode as $item) {
if ($item instanceof Expr && self::containsThisDependentExpression($item)) {
return true;
}
if ($item instanceof Arg && self::containsThisDependentExpression($item->value)) {
return true;
}
}
}
}
return false;
}
}