|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Symplify\PHPStanRules\Rules\PHPUnit; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Expr\MethodCall; |
| 9 | +use PhpParser\Node\Expr\PropertyFetch; |
| 10 | +use PhpParser\Node\Expr\Variable; |
| 11 | +use PHPStan\Analyser\Scope; |
| 12 | +use PHPStan\Rules\IdentifierRuleError; |
| 13 | +use PHPStan\Rules\Rule; |
| 14 | +use PHPStan\Rules\RuleErrorBuilder; |
| 15 | +use Symplify\PHPStanRules\Enum\RuleIdentifier\PHPUnitRuleIdentifier; |
| 16 | +use Symplify\PHPStanRules\Helper\NamingHelper; |
| 17 | +use Symplify\PHPStanRules\PHPUnit\TestClassDetector; |
| 18 | + |
| 19 | +/** |
| 20 | + * @implements Rule<MethodCall> |
| 21 | + * |
| 22 | + * @see \Symplify\PHPStanRules\Tests\Rules\PHPUnit\ExplicitExpectsMockMethodRule\ExplicitExpectsMockMethodRuleTest |
| 23 | + */ |
| 24 | +final class ExplicitExpectsMockMethodRule implements Rule |
| 25 | +{ |
| 26 | + public const string ERROR_MESSAGE = 'PHPUnit mock method is missing explicit expects(), e.g. $this->mock->expects($this->once())->...'; |
| 27 | + |
| 28 | + public function getNodeType(): string |
| 29 | + { |
| 30 | + return MethodCall::class; |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * @param MethodCall $node |
| 35 | + * @return IdentifierRuleError[] |
| 36 | + */ |
| 37 | + public function processNode(Node $node, Scope $scope): array |
| 38 | + { |
| 39 | + if (! NamingHelper::isName($node->name, 'method')) { |
| 40 | + return []; |
| 41 | + } |
| 42 | + |
| 43 | + if (! TestClassDetector::isTestClass($scope)) { |
| 44 | + return []; |
| 45 | + } |
| 46 | + |
| 47 | + if (! $node->var instanceof Variable && ! $node->var instanceof PropertyFetch) { |
| 48 | + return []; |
| 49 | + } |
| 50 | + |
| 51 | + $callerType = $scope->getType($node->var); |
| 52 | + if (! $callerType->hasMethod('expects')->yes()) { |
| 53 | + return []; |
| 54 | + } |
| 55 | + |
| 56 | + $identifierRuleError = RuleErrorBuilder::message(self::ERROR_MESSAGE) |
| 57 | + ->identifier(PHPUnitRuleIdentifier::NO_ASSERT_FUNC_CALL_IN_TESTS) |
| 58 | + ->build(); |
| 59 | + |
| 60 | + return [$identifierRuleError]; |
| 61 | + } |
| 62 | +} |
0 commit comments