-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathMockMethodCallRule.php
105 lines (86 loc) · 2.36 KB
/
MockMethodCallRule.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
<?php declare(strict_types = 1);
namespace PHPStan\Rules\PHPUnit;
use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\IdentifierRuleError;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\Type;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\MockObject\Stub;
use function array_filter;
use function count;
use function implode;
use function in_array;
use function sprintf;
/**
* @implements Rule<MethodCall>
*/
class MockMethodCallRule implements Rule
{
public function getNodeType(): string
{
return Node\Expr\MethodCall::class;
}
public function processNode(Node $node, Scope $scope): array
{
if (!$node->name instanceof Node\Identifier || $node->name->name !== 'method') {
return [];
}
if (count($node->getArgs()) < 1) {
return [];
}
$argType = $scope->getType($node->getArgs()[0]->value);
if (count($argType->getConstantStrings()) === 0) {
return [];
}
$errors = [];
foreach ($argType->getConstantStrings() as $constantString) {
$method = $constantString->getValue();
$type = $scope->getType($node->var);
$error = $this->checkCallOnType($type, $method);
if ($error !== null) {
$errors[] = $error;
continue;
}
if (!$node->var instanceof MethodCall) {
continue;
}
if (!$node->var->name instanceof Node\Identifier) {
continue;
}
if ($node->var->name->toLowerString() !== 'expects') {
continue;
}
$varType = $scope->getType($node->var->var);
$error = $this->checkCallOnType($varType, $method);
if ($error === null) {
continue;
}
$errors[] = $error;
}
return $errors;
}
private function checkCallOnType(Type $type, string $method): ?IdentifierRuleError
{
if (
(
in_array(MockObject::class, $type->getObjectClassNames(), true)
|| in_array(Stub::class, $type->getObjectClassNames(), true)
)
&& !$type->hasMethod($method)->yes()
) {
$mockClasses = array_filter($type->getObjectClassNames(), static fn (string $class): bool => $class !== MockObject::class && $class !== Stub::class);
if (count($mockClasses) === 0) {
return null;
}
return RuleErrorBuilder::message(sprintf(
'Trying to mock an undefined method %s() on class %s.',
$method,
implode('&', $mockClasses),
))->identifier('phpunit.mockMethod')->build();
}
return null;
}
}