Skip to content

Commit

Permalink
feat: Add PHPStan-Rule `MLL\Utils\PHPStan\Rules\ThrowableClassNameRul…
Browse files Browse the repository at this point in the history
…e` (#41)
  • Loading branch information
simbig authored Nov 14, 2024
1 parent 4f745da commit 36552aa
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ See [GitHub releases](https://github.com/mll-lab/php-utils/releases).

## Unreleased

## v5.8.0

### Added

- Add PHPStan-Rule `MLL\Utils\PHPStan\Rules\ThrowableClassNameRule`

## v5.7.0

### Added
Expand Down
56 changes: 56 additions & 0 deletions src/PHPStan/Rules/ThrowableClassNameRule.php
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 [];
}
}

0 comments on commit 36552aa

Please sign in to comment.