-
Notifications
You must be signed in to change notification settings - Fork 566
Expand file tree
/
Copy pathOverridingMethodRule.php
More file actions
373 lines (337 loc) · 12.1 KB
/
OverridingMethodRule.php
File metadata and controls
373 lines (337 loc) · 12.1 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
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Methods;
use PhpParser\Node;
use PhpParser\Node\Attribute;
use PHPStan\Analyser\CollectedDataEmitter;
use PHPStan\Analyser\NodeCallbackInvoker;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\AutowiredParameter;
use PHPStan\DependencyInjection\RegisteredRule;
use PHPStan\Node\InClassMethodNode;
use PHPStan\Php\PhpVersion;
use PHPStan\Reflection\ExtendedFunctionVariant;
use PHPStan\Reflection\MethodPrototypeReflection;
use PHPStan\Rules\IdentifierRuleError;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\MixedType;
use PHPStan\Type\VerbosityLevel;
use function array_merge;
use function count;
use function is_bool;
use function sprintf;
use function strtolower;
/**
* @implements Rule<InClassMethodNode>
*/
#[RegisteredRule(level: 0)]
final class OverridingMethodRule implements Rule
{
public function __construct(
private PhpVersion $phpVersion,
private MethodSignatureRule $methodSignatureRule,
#[AutowiredParameter]
private bool $checkPhpDocMethodSignatures,
private MethodParameterComparisonHelper $methodParameterComparisonHelper,
private MethodVisibilityComparisonHelper $methodVisibilityComparisonHelper,
private MethodPrototypeFinder $methodPrototypeFinder,
#[AutowiredParameter]
private bool $checkMissingOverrideMethodAttribute,
)
{
}
public function getNodeType(): string
{
return InClassMethodNode::class;
}
public function processNode(Node $node, Scope&NodeCallbackInvoker&CollectedDataEmitter $scope): array
{
$method = $node->getMethodReflection();
$prototypeData = $this->methodPrototypeFinder->findPrototype($node->getClassReflection(), $method->getName());
if ($prototypeData === null) {
if (strtolower($method->getName()) === '__construct') {
$parent = $method->getDeclaringClass()->getParentClass();
if ($parent !== null && $parent->hasConstructor()) {
$parentConstructor = $parent->getConstructor();
if ($parentConstructor->isFinalByKeyword()->yes()) {
return $this->addErrors([
RuleErrorBuilder::message(sprintf(
'Method %s::%s() overrides final method %s::%s().',
$method->getDeclaringClass()->getDisplayName(),
$method->getName(),
$parent->getDisplayName(true),
$parentConstructor->getName(),
))
->nonIgnorable()
->identifier('method.parentMethodFinal')
->build(),
], $node, $scope);
}
if ($parentConstructor->isFinal()->yes()) {
return $this->addErrors([
RuleErrorBuilder::message(sprintf(
'Method %s::%s() overrides @final method %s::%s().',
$method->getDeclaringClass()->getDisplayName(),
$method->getName(),
$parent->getDisplayName(true),
$parentConstructor->getName(),
))->identifier('method.parentMethodFinalByPhpDoc')
->build(),
], $node, $scope);
}
}
}
if ($this->hasOverrideAttribute($node->getOriginalNode())) {
return [
RuleErrorBuilder::message(sprintf(
'Method %s::%s() has #[\Override] attribute but does not override any method.',
$method->getDeclaringClass()->getDisplayName(),
$method->getName(),
))
->nonIgnorable()
->identifier('method.override')
->fixNode($node->getOriginalNode(), function (Node\Stmt\ClassMethod $method) {
$method->attrGroups = $this->filterOverrideAttribute($method->attrGroups);
return $method;
})
->build(),
];
}
return [];
}
[
$prototype,
$prototypeDeclaringClass,
$checkVisibility,
$inheritancePrototype,
$inheritancePrototypeDeclaringClass,
] = $prototypeData;
$messages = [];
if (
$this->checkMissingOverrideMethodAttribute
&& !$scope->isInTrait()
&& !$this->hasOverrideAttribute($node->getOriginalNode())
) {
$messages[] = RuleErrorBuilder::message(sprintf(
'Method %s::%s() overrides method %s::%s() but is missing the #[\Override] attribute.',
$method->getDeclaringClass()->getDisplayName(),
$method->getName(),
$inheritancePrototypeDeclaringClass->getDisplayName(true),
$inheritancePrototype->getName(),
))
->identifier('method.missingOverride')
->fixNode($node->getOriginalNode(), static function (Node\Stmt\ClassMethod $method) {
$method->attrGroups[] = new Node\AttributeGroup([
new Attribute(new Node\Name\FullyQualified('Override')),
]);
return $method;
})
->build();
}
if ($inheritancePrototype->isFinalByKeyword()->yes()) {
$messages[] = RuleErrorBuilder::message(sprintf(
'Method %s::%s() overrides final method %s::%s().',
$method->getDeclaringClass()->getDisplayName(),
$method->getName(),
$inheritancePrototypeDeclaringClass->getDisplayName(true),
$inheritancePrototype->getName(),
))
->nonIgnorable()
->identifier('method.parentMethodFinal')
->build();
} elseif ($inheritancePrototype->isFinal()->yes()) {
$messages[] = RuleErrorBuilder::message(sprintf(
'Method %s::%s() overrides @final method %s::%s().',
$method->getDeclaringClass()->getDisplayName(),
$method->getName(),
$inheritancePrototypeDeclaringClass->getDisplayName(true),
$inheritancePrototype->getName(),
))->identifier('method.parentMethodFinalByPhpDoc')
->build();
}
if ($prototype->isStatic()) {
if (!$method->isStatic()) {
$messages[] = RuleErrorBuilder::message(sprintf(
'Non-static method %s::%s() overrides static method %s::%s().',
$method->getDeclaringClass()->getDisplayName(),
$method->getName(),
$prototypeDeclaringClass->getDisplayName(true),
$prototype->getName(),
))
->nonIgnorable()
->identifier('method.nonStatic')
->build();
}
} elseif ($method->isStatic()) {
$messages[] = RuleErrorBuilder::message(sprintf(
'Static method %s::%s() overrides non-static method %s::%s().',
$method->getDeclaringClass()->getDisplayName(),
$method->getName(),
$prototypeDeclaringClass->getDisplayName(true),
$prototype->getName(),
))
->nonIgnorable()
->identifier('method.static')
->build();
}
if ($checkVisibility) {
$messages = array_merge($messages, $this->methodVisibilityComparisonHelper->compare($prototype, $prototypeDeclaringClass, $method));
}
$prototypeVariants = $prototype->getVariants();
if (count($prototypeVariants) !== 1) {
return $this->addErrors($messages, $node, $scope);
}
$prototypeVariant = $prototypeVariants[0];
$methodReturnType = $method->getNativeReturnType();
$realPrototype = $method->getPrototype();
if (
$realPrototype instanceof MethodPrototypeReflection
&& $this->phpVersion->hasTentativeReturnTypes()
&& $realPrototype->getTentativeReturnType() !== null
&& !$this->hasReturnTypeWillChangeAttribute($node->getOriginalNode())
&& count($prototypeDeclaringClass->getNativeReflection()->getMethod($prototype->getName())->getAttributes('ReturnTypeWillChange')) === 0
) {
if (!$this->methodParameterComparisonHelper->isReturnTypeCompatible($realPrototype->getTentativeReturnType(), $method->getNativeReturnType(), true)) {
$messages[] = RuleErrorBuilder::message(sprintf(
'Return type %s of method %s::%s() is not covariant with tentative return type %s of method %s::%s().',
$methodReturnType->describe(VerbosityLevel::typeOnly()),
$method->getDeclaringClass()->getDisplayName(),
$method->getName(),
$realPrototype->getTentativeReturnType()->describe(VerbosityLevel::typeOnly()),
$realPrototype->getDeclaringClass()->getDisplayName(true),
$realPrototype->getName(),
))
->tip('Make it covariant, or use the #[\ReturnTypeWillChange] attribute to temporarily suppress the error.')
->nonIgnorable()
->identifier('method.tentativeReturnType')
->build();
}
}
$messages = array_merge($messages, $this->methodParameterComparisonHelper->compare($prototype, $prototypeDeclaringClass, $method, false));
if (!$prototypeVariant instanceof ExtendedFunctionVariant) {
return $this->addErrors($messages, $node, $scope);
}
$prototypeReturnType = $prototypeVariant->getNativeReturnType();
$reportReturnType = true;
if ($this->phpVersion->hasTentativeReturnTypes()) {
$reportReturnType = !$realPrototype instanceof MethodPrototypeReflection
|| $realPrototype->getTentativeReturnType() === null
|| (is_bool($prototype->isBuiltin()) ? !$prototype->isBuiltin() : $prototype->isBuiltin()->no());
} else {
if ($realPrototype instanceof MethodPrototypeReflection && $realPrototype->isInternal()) {
if (
(is_bool($prototype->isBuiltin()) ? $prototype->isBuiltin() : $prototype->isBuiltin()->yes())
&& $prototypeDeclaringClass->getName() !== $realPrototype->getDeclaringClass()->getName()
) {
$realPrototypeVariant = $realPrototype->getVariants()[0];
if (
$prototypeReturnType instanceof MixedType
&& !$prototypeReturnType->isExplicitMixed()
&& (!$realPrototypeVariant->getReturnType() instanceof MixedType || $realPrototypeVariant->getReturnType()->isExplicitMixed())
) {
$reportReturnType = false;
}
}
if (
$reportReturnType
&& (is_bool($prototype->isBuiltin()) ? $prototype->isBuiltin() : $prototype->isBuiltin()->yes())
) {
$reportReturnType = !$this->hasReturnTypeWillChangeAttribute($node->getOriginalNode());
}
}
}
if (
$reportReturnType
&& !$this->methodParameterComparisonHelper->isReturnTypeCompatible($prototypeReturnType, $methodReturnType, $this->phpVersion->supportsReturnCovariance())
) {
if ($this->phpVersion->supportsReturnCovariance()) {
$messages[] = RuleErrorBuilder::message(sprintf(
'Return type %s of method %s::%s() is not covariant with return type %s of method %s::%s().',
$methodReturnType->describe(VerbosityLevel::typeOnly()),
$method->getDeclaringClass()->getDisplayName(),
$method->getName(),
$prototypeReturnType->describe(VerbosityLevel::typeOnly()),
$prototypeDeclaringClass->getDisplayName(true),
$prototype->getName(),
))
->nonIgnorable()
->identifier('method.childReturnType')
->build();
} else {
$messages[] = RuleErrorBuilder::message(sprintf(
'Return type %s of method %s::%s() is not compatible with return type %s of method %s::%s().',
$methodReturnType->describe(VerbosityLevel::typeOnly()),
$method->getDeclaringClass()->getDisplayName(),
$method->getName(),
$prototypeReturnType->describe(VerbosityLevel::typeOnly()),
$prototypeDeclaringClass->getDisplayName(true),
$prototype->getName(),
))
->nonIgnorable()
->identifier('method.childReturnType')
->build();
}
}
return $this->addErrors($messages, $node, $scope);
}
/**
* @param Node\AttributeGroup[] $attrGroups
* @return Node\AttributeGroup[]
*/
private function filterOverrideAttribute(array $attrGroups): array
{
foreach ($attrGroups as $i => $attrGroup) {
foreach ($attrGroup->attrs as $j => $attr) {
if ($attr->name->toLowerString() !== 'override') {
continue;
}
unset($attrGroup->attrs[$j]);
if (count($attrGroup->attrs) !== 0) {
continue;
}
unset($attrGroups[$i]);
}
}
return $attrGroups;
}
/**
* @param list<IdentifierRuleError> $errors
* @return list<IdentifierRuleError>
*/
private function addErrors(
array $errors,
InClassMethodNode $classMethod,
Scope&NodeCallbackInvoker&CollectedDataEmitter $scope,
): array
{
if (count($errors) > 0) {
return $errors;
}
if (!$this->checkPhpDocMethodSignatures) {
return $errors;
}
return $this->methodSignatureRule->processNode($classMethod, $scope);
}
private function hasReturnTypeWillChangeAttribute(Node\Stmt\ClassMethod $method): bool
{
foreach ($method->attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attr) {
if ($attr->name->toLowerString() === 'returntypewillchange') {
return true;
}
}
}
return false;
}
private function hasOverrideAttribute(Node\Stmt\ClassMethod $method): bool
{
foreach ($method->attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attr) {
if ($attr->name->toLowerString() === 'override') {
return true;
}
}
}
return false;
}
}