|
| 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\ObjectType; |
| 8 | + |
| 9 | +class AssertSameDifferentTypesRule implements \PHPStan\Rules\Rule |
| 10 | +{ |
| 11 | + |
| 12 | + public function getNodeType(): string |
| 13 | + { |
| 14 | + return \PhpParser\NodeAbstract::class; |
| 15 | + } |
| 16 | + |
| 17 | + /** |
| 18 | + * @param \PhpParser\Node\Expr\MethodCall|\PhpParser\Node\Expr\StaticCall $node |
| 19 | + * @param \PHPStan\Analyser\Scope $scope |
| 20 | + * @return string[] errors |
| 21 | + */ |
| 22 | + public function processNode(Node $node, Scope $scope): array |
| 23 | + { |
| 24 | + $testCaseType = new ObjectType(\PHPUnit\Framework\TestCase::class); |
| 25 | + if ($node instanceof Node\Expr\MethodCall) { |
| 26 | + $calledOnType = $scope->getType($node->var); |
| 27 | + } elseif ($node instanceof Node\Expr\StaticCall) { |
| 28 | + if ($node->class instanceof Node\Name) { |
| 29 | + $class = (string) $node->class; |
| 30 | + if (in_array( |
| 31 | + strtolower($class), |
| 32 | + [ |
| 33 | + 'self', |
| 34 | + 'static', |
| 35 | + 'parent', |
| 36 | + ], |
| 37 | + true |
| 38 | + )) { |
| 39 | + $calledOnType = new ObjectType($scope->getClassReflection()->getName()); |
| 40 | + } else { |
| 41 | + $calledOnType = new ObjectType($class); |
| 42 | + } |
| 43 | + } else { |
| 44 | + $calledOnType = $scope->getType($node->class); |
| 45 | + } |
| 46 | + } else { |
| 47 | + return []; |
| 48 | + } |
| 49 | + |
| 50 | + if (!$testCaseType->isSupersetOf($calledOnType)->yes()) { |
| 51 | + return []; |
| 52 | + } |
| 53 | + |
| 54 | + if (count($node->args) < 2) { |
| 55 | + return []; |
| 56 | + } |
| 57 | + if (!is_string($node->name) || strtolower($node->name) !== 'assertsame') { |
| 58 | + return []; |
| 59 | + } |
| 60 | + |
| 61 | + $leftType = $scope->getType($node->args[0]->value); |
| 62 | + $rightType = $scope->getType($node->args[1]->value); |
| 63 | + |
| 64 | + if ($leftType->isSupersetOf($rightType)->no()) { |
| 65 | + return [ |
| 66 | + sprintf( |
| 67 | + 'Call to assertSame() with different types %s and %s will always result in test failure.', |
| 68 | + $leftType->describe(), |
| 69 | + $rightType->describe() |
| 70 | + ), |
| 71 | + ]; |
| 72 | + } |
| 73 | + |
| 74 | + return []; |
| 75 | + } |
| 76 | + |
| 77 | +} |
0 commit comments