|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Rules\PHPUnit; |
| 4 | + |
| 5 | +use PhpParser\Node; |
| 6 | +use PHPStan\Analyser\Scope; |
| 7 | +use PHPStan\Type\Constant\ConstantStringType; |
| 8 | +use PHPStan\Type\Generic\GenericObjectType; |
| 9 | +use PHPStan\Type\IntersectionType; |
| 10 | +use PHPStan\Type\ObjectType; |
| 11 | +use PHPUnit\Framework\MockObject\InvocationMocker; |
| 12 | +use PHPUnit\Framework\MockObject\MockObject; |
| 13 | + |
| 14 | +/** |
| 15 | + * @implements \PHPStan\Rules\Rule<\PhpParser\Node\Expr\MethodCall> |
| 16 | + */ |
| 17 | +class MockMethodCallRule implements \PHPStan\Rules\Rule |
| 18 | +{ |
| 19 | + |
| 20 | + public function getNodeType(): string |
| 21 | + { |
| 22 | + return Node\Expr\MethodCall::class; |
| 23 | + } |
| 24 | + |
| 25 | + public function processNode(Node $node, Scope $scope): array |
| 26 | + { |
| 27 | + /** @var Node\Expr\MethodCall $node */ |
| 28 | + $node = $node; |
| 29 | + |
| 30 | + if (!$node->name instanceof Node\Identifier || $node->name->name !== 'method') { |
| 31 | + return []; |
| 32 | + } |
| 33 | + |
| 34 | + if (count($node->args) < 1) { |
| 35 | + return []; |
| 36 | + } |
| 37 | + |
| 38 | + $argType = $scope->getType($node->args[0]->value); |
| 39 | + if (!($argType instanceof ConstantStringType)) { |
| 40 | + return []; |
| 41 | + } |
| 42 | + |
| 43 | + $method = $argType->getValue(); |
| 44 | + $type = $scope->getType($node->var); |
| 45 | + |
| 46 | + if ( |
| 47 | + $type instanceof IntersectionType |
| 48 | + && in_array(MockObject::class, $type->getReferencedClasses(), true) |
| 49 | + && !$type->hasMethod($method)->yes() |
| 50 | + ) { |
| 51 | + $mockClass = array_filter($type->getReferencedClasses(), function (string $class): bool { |
| 52 | + return $class !== MockObject::class; |
| 53 | + }); |
| 54 | + |
| 55 | + return [ |
| 56 | + sprintf( |
| 57 | + 'Trying to mock an undefined method %s() on class %s.', |
| 58 | + $method, |
| 59 | + \implode('&', $mockClass) |
| 60 | + ), |
| 61 | + ]; |
| 62 | + } |
| 63 | + |
| 64 | + if ( |
| 65 | + $type instanceof GenericObjectType |
| 66 | + && $type->getClassName() === InvocationMocker::class |
| 67 | + && count($type->getTypes()) > 0 |
| 68 | + ) { |
| 69 | + $mockClass = $type->getTypes()[0]; |
| 70 | + |
| 71 | + if ($mockClass instanceof ObjectType && !$mockClass->hasMethod($method)->yes()) { |
| 72 | + return [ |
| 73 | + sprintf( |
| 74 | + 'Trying to mock an undefined method %s() on class %s.', |
| 75 | + $method, |
| 76 | + $mockClass->getClassName() |
| 77 | + ), |
| 78 | + ]; |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + return []; |
| 83 | + } |
| 84 | + |
| 85 | +} |
0 commit comments