forked from phpstan/phpstan-strict-rules
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVariablePropertyFetchRule.php
More file actions
98 lines (81 loc) · 2.23 KB
/
VariablePropertyFetchRule.php
File metadata and controls
98 lines (81 loc) · 2.23 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
89
90
91
92
93
94
95
96
97
98
<?php declare(strict_types = 1);
namespace PHPStan\Rules\VariableVariables;
use PhpParser\Node;
use PhpParser\Node\Expr\PropertyFetch;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\VerbosityLevel;
use SimpleXMLElement;
use function sprintf;
/**
* @implements Rule<PropertyFetch>
*/
class VariablePropertyFetchRule implements Rule
{
private ReflectionProvider $reflectionProvider;
/** @var string[] */
private array $universalObjectCratesClasses;
/**
* @param string[] $universalObjectCratesClasses
*/
public function __construct(ReflectionProvider $reflectionProvider, array $universalObjectCratesClasses)
{
$this->reflectionProvider = $reflectionProvider;
$this->universalObjectCratesClasses = $universalObjectCratesClasses;
}
public function getNodeType(): string
{
return PropertyFetch::class;
}
public function processNode(Node $node, Scope $scope): array
{
if ($node->name instanceof Node\Identifier) {
return [];
}
if ($scope->getType($node->name)->isLiteralString()->yes()) {
return [];
}
$fetchedOnType = $scope->getType($node->var);
foreach ($fetchedOnType->getObjectClassNames() as $referencedClass) {
if (!$this->reflectionProvider->hasClass($referencedClass)) {
continue;
}
$classReflection = $this->reflectionProvider->getClass($referencedClass);
if (
$this->isUniversalObjectCrate($classReflection)
|| $this->isSimpleXMLElement($classReflection)
) {
return [];
}
}
return [
RuleErrorBuilder::message(sprintf(
'Variable property access on %s.',
$fetchedOnType->describe(VerbosityLevel::typeOnly()),
))->identifier('property.dynamicName')->build(),
];
}
private function isSimpleXMLElement(
ClassReflection $classReflection
): bool
{
return $classReflection->is(SimpleXMLElement::class);
}
private function isUniversalObjectCrate(
ClassReflection $classReflection
): bool
{
foreach ($this->universalObjectCratesClasses as $className) {
if (!$this->reflectionProvider->hasClass($className)) {
continue;
}
if ($classReflection->is($className)) {
return true;
}
}
return false;
}
}