|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Lendable\PHPUnitExtensions\Phpstan\Rule; |
| 6 | + |
| 7 | +use Lendable\PHPUnitExtensions\StrictMocking as StrictMockingTrait; |
| 8 | +use Lendable\PHPUnitExtensions\TestCase as StrictMockingTestCase; |
| 9 | +use PhpParser\Node; |
| 10 | +use PhpParser\Node\Name; |
| 11 | +use PhpParser\Node\Stmt\Class_; |
| 12 | +use PHPStan\Analyser\Scope; |
| 13 | +use PHPStan\Reflection\ClassReflection; |
| 14 | +use PHPStan\Rules\Rule; |
| 15 | +use PHPStan\Rules\RuleErrorBuilder; |
| 16 | +use PHPUnit\Framework\TestCase; |
| 17 | + |
| 18 | +/** |
| 19 | + * @implements Rule<Class_> |
| 20 | + */ |
| 21 | +final class EnforceStrictMocking implements Rule |
| 22 | +{ |
| 23 | + /** |
| 24 | + * @var array<class-string, int> |
| 25 | + */ |
| 26 | + private readonly array $pardoned; |
| 27 | + |
| 28 | + /** |
| 29 | + * @param list<class-string> $pardoned |
| 30 | + */ |
| 31 | + public function __construct(array $pardoned) |
| 32 | + { |
| 33 | + $this->pardoned = \array_flip($pardoned); |
| 34 | + } |
| 35 | + |
| 36 | + public function getNodeType(): string |
| 37 | + { |
| 38 | + return Class_::class; |
| 39 | + } |
| 40 | + |
| 41 | + public function processNode(Node $node, Scope $scope): array |
| 42 | + { |
| 43 | + if (!$node->namespacedName instanceof Name) { |
| 44 | + return []; |
| 45 | + } |
| 46 | + |
| 47 | + if (!$node->extends instanceof Name) { |
| 48 | + return []; |
| 49 | + } |
| 50 | + |
| 51 | + if ($node->isAbstract()) { |
| 52 | + return []; |
| 53 | + } |
| 54 | + |
| 55 | + $className = $node->namespacedName->toString(); |
| 56 | + if (!\str_ends_with($className, 'Test')) { |
| 57 | + return []; |
| 58 | + } |
| 59 | + |
| 60 | + if (isset($this->pardoned[$className])) { |
| 61 | + return []; |
| 62 | + } |
| 63 | + |
| 64 | + $reflection = $scope->resolveTypeByName($node->namespacedName)->getClassReflection(); |
| 65 | + if (!$reflection instanceof ClassReflection) { |
| 66 | + return []; |
| 67 | + } |
| 68 | + |
| 69 | + $parents = $reflection->getParentClassesNames(); |
| 70 | + if (!\in_array(TestCase::class, $parents, true)) { |
| 71 | + return []; |
| 72 | + } |
| 73 | + |
| 74 | + if (\in_array(StrictMockingTestCase::class, $parents, true)) { |
| 75 | + return []; |
| 76 | + } |
| 77 | + |
| 78 | + if (isset($reflection->getTraits(true)[StrictMockingTrait::class])) { |
| 79 | + return []; |
| 80 | + } |
| 81 | + |
| 82 | + $ruleErrorBuilder = RuleErrorBuilder::message(\sprintf( |
| 83 | + 'Class "%s" must either extend "%s" or use "%s" trait.', |
| 84 | + $className, |
| 85 | + StrictMockingTestCase::class, |
| 86 | + StrictMockingTrait::class, |
| 87 | + )); |
| 88 | + |
| 89 | + return [$ruleErrorBuilder->build()]; |
| 90 | + } |
| 91 | +} |
0 commit comments