Skip to content

Commit

Permalink
feat: Add PHPStan-Rule MLL\Utils\PHPStan\Rules\ThrowableClassNameRule
Browse files Browse the repository at this point in the history
  • Loading branch information
Simon Bigelmayr committed Nov 14, 2024
1 parent 3371142 commit 2509a58
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@ 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

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

## v5.6.0

### Added
Expand Down
51 changes: 51 additions & 0 deletions src/PHPStan/Rules/ThrowableClassNameRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php declare(strict_types=1);

namespace MLL\Utils\PHPStan\Rules;

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
{
$className = (string) $node->name;
$extendsThrowable = false;

if ($node->extends !== null) {
$parentClass = $node->extends->toString();
$extendsThrowable = is_subclass_of($parentClass, \Throwable::class) || $parentClass === \Throwable::class;
}

if ($extendsThrowable && ! str_ends_with($className, 'Exception')) {
return [
RuleErrorBuilder::message(sprintf(
'Class "%s" extends \Throwable but does not use the suffix "Exception".',
$className
))->build(),
];
}

if (! $extendsThrowable && str_ends_with($className, 'Exception')) {
return [
RuleErrorBuilder::message(sprintf(
'Class "%s" uses the suffix "Exception" but does not extend \Throwable. Consider using "Exemption" or another term.',
$className
))->build(),
];
}

return [];
}
}

0 comments on commit 2509a58

Please sign in to comment.