gacela-project /
gacela
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace Gacela\PHPStan\Rules; |
||
| 6 | |||
| 7 | use PhpParser\Node; |
||
| 8 | use PhpParser\Node\Stmt\Class_; |
||
| 9 | use PHPStan\Analyser\Scope; |
||
| 10 | use PHPStan\Reflection\ClassReflection; |
||
| 11 | use PHPStan\Rules\Rule; |
||
| 12 | |||
| 13 | use function sprintf; |
||
| 14 | |||
| 15 | /** |
||
| 16 | * @implements Rule<Class_> |
||
| 17 | */ |
||
| 18 | final class SuffixExtendsRule implements Rule |
||
| 19 | { |
||
| 20 | public function __construct( |
||
| 21 | private readonly string $suffix, |
||
| 22 | private readonly string $expectedParent, |
||
| 23 | ) { |
||
| 24 | } |
||
| 25 | |||
| 26 | public function getNodeType(): string |
||
| 27 | { |
||
| 28 | return Class_::class; |
||
| 29 | } |
||
| 30 | |||
| 31 | public function processNode(Node $node, Scope $scope): array |
||
| 32 | { |
||
| 33 | if ($node->isAnonymous()) { |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 34 | return []; |
||
| 35 | } |
||
| 36 | |||
| 37 | $classReflection = $scope->getClassReflection(); |
||
| 38 | if (!$classReflection instanceof ClassReflection) { |
||
| 39 | return []; |
||
| 40 | } |
||
| 41 | |||
| 42 | $className = $classReflection->getName(); |
||
| 43 | $pos = strrpos($className, '\\'); |
||
| 44 | $shortName = $pos === false ? $className : substr($className, $pos + 1); |
||
| 45 | |||
| 46 | if (!str_ends_with($shortName, $this->suffix)) { |
||
| 47 | return []; |
||
| 48 | } |
||
| 49 | |||
| 50 | if ( |
||
| 51 | $className !== $this->expectedParent && |
||
| 52 | !$classReflection->isSubclassOf($this->expectedParent) |
||
| 53 | ) { |
||
| 54 | return [sprintf('Class %s should extend %s', $className, $this->expectedParent)]; |
||
| 55 | } |
||
| 56 | |||
| 57 | return []; |
||
| 58 | } |
||
| 59 | } |
||
| 60 |