-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathShouldCallParentMethodsRule.php
108 lines (86 loc) · 2.18 KB
/
ShouldCallParentMethodsRule.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
<?php declare(strict_types = 1);
namespace PHPStan\Rules\PHPUnit;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Node\InClassMethodNode;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPUnit\Framework\TestCase;
use function in_array;
use function sprintf;
use function strtolower;
/**
* @implements Rule<InClassMethodNode>
*/
class ShouldCallParentMethodsRule implements Rule
{
public function getNodeType(): string
{
return InClassMethodNode::class;
}
public function processNode(Node $node, Scope $scope): array
{
$methodName = $node->getOriginalNode()->name->name;
if (!in_array(strtolower($methodName), ['setup', 'teardown'], true)) {
return [];
}
if ($scope->getClassReflection() === null) {
return [];
}
if (!$scope->getClassReflection()->is(TestCase::class)) {
return [];
}
$parentClass = $scope->getClassReflection()->getParentClass();
if ($parentClass === null) {
return [];
}
if (!$parentClass->hasNativeMethod($methodName)) {
return [];
}
$parentMethod = $parentClass->getNativeMethod($methodName);
if ($parentMethod->getDeclaringClass()->getName() === TestCase::class) {
return [];
}
$hasParentCall = $this->hasParentClassCall($node->getOriginalNode()->getStmts(), strtolower($methodName));
if (!$hasParentCall) {
return [
RuleErrorBuilder::message(
sprintf('Missing call to parent::%s() method.', $methodName),
)->identifier('phpunit.callParent')->build(),
];
}
return [];
}
/**
* @param Node\Stmt[]|null $stmts
*
*/
private function hasParentClassCall(?array $stmts, string $methodName): bool
{
if ($stmts === null) {
return false;
}
foreach ($stmts as $stmt) {
if (! $stmt instanceof Node\Stmt\Expression) {
continue;
}
if (! $stmt->expr instanceof Node\Expr\StaticCall) {
continue;
}
if (! $stmt->expr->class instanceof Node\Name) {
continue;
}
$class = (string) $stmt->expr->class;
if (strtolower($class) !== 'parent') {
continue;
}
if (! $stmt->expr->name instanceof Node\Identifier) {
continue;
}
if ($stmt->expr->name->toLowerString() === $methodName) {
return true;
}
}
return false;
}
}