|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace MLL\Utils\PHPStan\Rules; |
| 4 | + |
| 5 | +use Illuminate\Support\Str; |
| 6 | +use PhpParser\Node; |
| 7 | +use PhpParser\Node\Stmt\Class_; |
| 8 | +use PHPStan\Analyser\Scope; |
| 9 | +use PHPStan\Rules\Rule; |
| 10 | +use PHPStan\Rules\RuleErrorBuilder; |
| 11 | + |
| 12 | +/** @implements Rule<Class_> */ |
| 13 | +class ThrowableClassNameRule implements Rule |
| 14 | +{ |
| 15 | + public function getNodeType(): string |
| 16 | + { |
| 17 | + return Class_::class; |
| 18 | + } |
| 19 | + |
| 20 | + public function processNode(Node $node, Scope $scope): array |
| 21 | + { |
| 22 | + $nodeName = $node->name; |
| 23 | + if ($nodeName === null) { |
| 24 | + return []; |
| 25 | + } |
| 26 | + |
| 27 | + $className = $nodeName->name; |
| 28 | + |
| 29 | + $extends = $node->extends; |
| 30 | + if ($extends === null) { |
| 31 | + if (Str::endsWith($className, 'Exception')) { |
| 32 | + return [ |
| 33 | + RuleErrorBuilder::message(<<<TXT |
| 34 | + Class "{$className}" is suffixed with "Exception" but does not extend \Exception. Consider using "Exemption" or another term. |
| 35 | + TXT)->build(), |
| 36 | + ]; |
| 37 | + } |
| 38 | + |
| 39 | + return []; |
| 40 | + } |
| 41 | + |
| 42 | + $parentClass = $extends->toString(); |
| 43 | + $extendsThrowable = is_subclass_of($parentClass, \Exception::class) |
| 44 | + || $parentClass === \Exception::class; |
| 45 | + |
| 46 | + if ($extendsThrowable && ! Str::endsWith($className, 'Exception')) { |
| 47 | + return [ |
| 48 | + RuleErrorBuilder::message(<<<TXT |
| 49 | + Class "{$className}" extends \Exception but is not suffixed with "Exception". |
| 50 | + TXT)->build(), |
| 51 | + ]; |
| 52 | + } |
| 53 | + |
| 54 | + return []; |
| 55 | + } |
| 56 | +} |
0 commit comments