forked from phpstan/phpstan-src
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClassConstantRule.php
239 lines (213 loc) · 7.1 KB
/
ClassConstantRule.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Classes;
use PhpParser\Node;
use PhpParser\Node\Expr\ClassConstFetch;
use PHPStan\Analyser\NullsafeOperatorHelper;
use PHPStan\Analyser\Scope;
use PHPStan\Internal\SprintfHelper;
use PHPStan\Php\PhpVersion;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\ClassNameCheck;
use PHPStan\Rules\ClassNameNodePair;
use PHPStan\Rules\IdentifierRuleError;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Rules\RuleLevelHelper;
use PHPStan\Type\ErrorType;
use PHPStan\Type\StringType;
use PHPStan\Type\ThisType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\VerbosityLevel;
use function array_map;
use function array_merge;
use function in_array;
use function sprintf;
use function strtolower;
/**
* @implements Rule<Node\Expr\ClassConstFetch>
*/
final class ClassConstantRule implements Rule
{
public function __construct(
private ReflectionProvider $reflectionProvider,
private RuleLevelHelper $ruleLevelHelper,
private ClassNameCheck $classCheck,
private PhpVersion $phpVersion,
)
{
}
public function getNodeType(): string
{
return ClassConstFetch::class;
}
public function processNode(Node $node, Scope $scope): array
{
$errors = [];
if ($node->name instanceof Node\Identifier) {
$constantNames = [$node->name->name];
} else {
$fetchType = $scope->getType($node->name);
$constantNames = array_map(static fn ($type): string => $type->getValue(), $fetchType->getConstantStrings());
}
foreach ($constantNames as $constantName) {
$errors = array_merge($errors, $this->processSingleClassConstFetch($scope, $node, $constantName));
}
return $errors;
}
/**
* @return list<IdentifierRuleError>
*/
private function processSingleClassConstFetch(Scope $scope, ClassConstFetch $node, string $constantName): array
{
$class = $node->class;
$messages = [];
if ($class instanceof Node\Name) {
$className = (string) $class;
$lowercasedClassName = strtolower($className);
if (in_array($lowercasedClassName, ['self', 'static'], true)) {
if (!$scope->isInClass()) {
return [
RuleErrorBuilder::message(sprintf('Using %s outside of class scope.', $className))
->identifier(sprintf('outOfClass.%s', $lowercasedClassName))
->build(),
];
}
$classType = $scope->resolveTypeByName($class);
} elseif ($lowercasedClassName === 'parent') {
if (!$scope->isInClass()) {
return [
RuleErrorBuilder::message(sprintf('Using %s outside of class scope.', $className))
->identifier(sprintf('outOfClass.%s', $lowercasedClassName))
->build(),
];
}
$currentClassReflection = $scope->getClassReflection();
if ($currentClassReflection->getParentClass() === null) {
return [
RuleErrorBuilder::message(sprintf(
'Access to parent::%s but %s does not extend any class.',
$constantName,
$currentClassReflection->getDisplayName(),
))->identifier('class.noParent')->build(),
];
}
$classType = $scope->resolveTypeByName($class);
} else {
if (!$this->reflectionProvider->hasClass($className)) {
if ($scope->isInClassExists($className)) {
return [];
}
if (strtolower($constantName) === 'class') {
return [
RuleErrorBuilder::message(sprintf('Class %s not found.', $className))
->identifier('class.notFound')
->discoveringSymbolsTip()
->build(),
];
}
return [
RuleErrorBuilder::message(
sprintf('Access to constant %s on an unknown class %s.', $constantName, $className),
)
->identifier('class.notFound')
->discoveringSymbolsTip()
->build(),
];
}
$classType = $scope->resolveTypeByName($class);
if (strtolower($constantName) !== 'class') {
foreach ($classType->getObjectClassReflections() as $classTypeReflection) {
if (!$classTypeReflection->isTrait()) {
continue;
}
return [
RuleErrorBuilder::message(sprintf(
'Cannot access constant %s on trait %s.',
$constantName,
$classTypeReflection->getDisplayName(),
))->identifier('classConstant.onTrait')->build(),
];
}
}
$messages = $this->classCheck->checkClassNames([new ClassNameNodePair($className, $class)]);
}
if (strtolower($constantName) === 'class') {
return $messages;
}
} else {
$classTypeResult = $this->ruleLevelHelper->findTypeToCheck(
$scope,
NullsafeOperatorHelper::getNullsafeShortcircuitedExprRespectingScope($scope, $class),
sprintf('Access to constant %s on an unknown class %%s.', SprintfHelper::escapeFormatString($constantName)),
static fn (Type $type): bool => $type->canAccessConstants()->yes() && $type->hasConstant($constantName)->yes(),
);
$classType = $classTypeResult->getType();
if ($classType instanceof ErrorType) {
return $classTypeResult->getUnknownClassErrors();
}
if (strtolower($constantName) === 'class') {
if (!$this->phpVersion->supportsClassConstantOnExpression()) {
return [
RuleErrorBuilder::message('Accessing ::class constant on an expression is supported only on PHP 8.0 and later.')
->identifier('classConstant.notSupported')
->nonIgnorable()
->build(),
];
}
if (!$class instanceof Node\Scalar\String_ && $classType->isString()->yes()) {
return [
RuleErrorBuilder::message('Accessing ::class constant on a dynamic string is not supported in PHP.')
->identifier('classConstant.dynamicString')
->nonIgnorable()
->build(),
];
}
}
}
if ($classType->isString()->yes()) {
return $messages;
}
$typeForDescribe = $classType;
if ($classType instanceof ThisType) {
$typeForDescribe = $classType->getStaticObjectType();
}
$classType = TypeCombinator::remove($classType, new StringType());
if (!$classType->canAccessConstants()->yes()) {
return array_merge($messages, [
RuleErrorBuilder::message(sprintf(
'Cannot access constant %s on %s.',
$constantName,
$typeForDescribe->describe(VerbosityLevel::typeOnly()),
))->identifier('classConstant.nonObject')->build(),
]);
}
if (strtolower($constantName) === 'class' || $scope->hasExpressionType($node)->yes()) {
return $messages;
}
if (!$classType->hasConstant($constantName)->yes()) {
return array_merge($messages, [
RuleErrorBuilder::message(sprintf(
'Access to undefined constant %s::%s.',
$typeForDescribe->describe(VerbosityLevel::typeOnly()),
$constantName,
))->identifier('classConstant.notFound')->build(),
]);
}
$constantReflection = $classType->getConstant($constantName);
if (!$scope->canAccessConstant($constantReflection)) {
return array_merge($messages, [
RuleErrorBuilder::message(sprintf(
'Access to %s constant %s of class %s.',
$constantReflection->isPrivate() ? 'private' : 'protected',
$constantName,
$constantReflection->getDeclaringClass()->getDisplayName(),
))->identifier(sprintf(
'classConstant.%s',
$constantReflection->isPrivate() ? 'private' : 'protected',
))->build(),
]);
}
return $messages;
}
}