forked from phpstan/phpstan-phpunit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMockMethodCallRule.php
85 lines (70 loc) · 1.92 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
<?php declare(strict_types = 1);
namespace PHPStan\Rules\PHPUnit;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\Generic\GenericObjectType;
use PHPStan\Type\IntersectionType;
use PHPStan\Type\ObjectType;
use PHPUnit\Framework\MockObject\Builder\InvocationMocker;
use PHPUnit\Framework\MockObject\MockObject;
/**
* @implements \PHPStan\Rules\Rule<\PhpParser\Node\Expr\MethodCall>
*/
class MockMethodCallRule implements \PHPStan\Rules\Rule
{
public function getNodeType(): string
{
return Node\Expr\MethodCall::class;
}
public function processNode(Node $node, Scope $scope): array
{
/** @var Node\Expr\MethodCall $node */
$node = $node;
if (!$node->name instanceof Node\Identifier || $node->name->name !== 'method') {
return [];
}
if (count($node->args) < 1) {
return [];
}
$argType = $scope->getType($node->args[0]->value);
if (!($argType instanceof ConstantStringType)) {
return [];
}
$method = $argType->getValue();
$type = $scope->getType($node->var);
if (
$type instanceof IntersectionType
&& in_array(MockObject::class, $type->getReferencedClasses(), true)
&& !$type->hasMethod($method)->yes()
) {
$mockClass = array_filter($type->getReferencedClasses(), function (string $class): bool {
return $class !== MockObject::class;
});
return [
sprintf(
'Trying to mock an undefined method %s() on class %s.',
$method,
\implode('&', $mockClass)
),
];
}
if (
$type instanceof GenericObjectType
&& $type->getClassName() === InvocationMocker::class
&& count($type->getTypes()) > 0
) {
$mockClass = $type->getTypes()[0];
if ($mockClass instanceof ObjectType && !$mockClass->hasMethod($method)->yes()) {
return [
sprintf(
'Trying to mock an undefined method %s() on class %s.',
$method,
$mockClass->getClassName()
),
];
}
}
return [];
}
}