generated from spawnia/php-package-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add PHPStan-Rule `MLL\Utils\PHPStan\Rules\ThrowableClassNameRul…
…e` (#41)
- Loading branch information
Showing
2 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
<?php declare(strict_types=1); | ||
|
||
namespace MLL\Utils\PHPStan\Rules; | ||
|
||
use Illuminate\Support\Str; | ||
use PhpParser\Node; | ||
use PhpParser\Node\Stmt\Class_; | ||
use PHPStan\Analyser\Scope; | ||
use PHPStan\Rules\Rule; | ||
use PHPStan\Rules\RuleErrorBuilder; | ||
|
||
/** @implements Rule<Class_> */ | ||
class ThrowableClassNameRule implements Rule | ||
{ | ||
public function getNodeType(): string | ||
{ | ||
return Class_::class; | ||
} | ||
|
||
public function processNode(Node $node, Scope $scope): array | ||
{ | ||
$nodeName = $node->name; | ||
if ($nodeName === null) { | ||
return []; | ||
} | ||
|
||
$className = $nodeName->name; | ||
|
||
$extends = $node->extends; | ||
if ($extends === null) { | ||
if (Str::endsWith($className, 'Exception')) { | ||
return [ | ||
RuleErrorBuilder::message(<<<TXT | ||
Class "{$className}" is suffixed with "Exception" but does not extend \Exception. Consider using "Exemption" or another term. | ||
TXT)->build(), | ||
]; | ||
} | ||
|
||
return []; | ||
} | ||
|
||
$parentClass = $extends->toString(); | ||
$extendsThrowable = is_subclass_of($parentClass, \Exception::class) | ||
|| $parentClass === \Exception::class; | ||
|
||
if ($extendsThrowable && ! Str::endsWith($className, 'Exception')) { | ||
return [ | ||
RuleErrorBuilder::message(<<<TXT | ||
Class "{$className}" extends \Exception but is not suffixed with "Exception". | ||
TXT)->build(), | ||
]; | ||
} | ||
|
||
return []; | ||
} | ||
} |