|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * @copyright Copyright (C) Ibexa AS. All rights reserved. |
| 5 | + * @license For full copyright and license information view LICENSE file distributed with this source code. |
| 6 | + */ |
| 7 | +declare(strict_types=1); |
| 8 | + |
| 9 | +namespace Ibexa\PHPStan\Rules; |
| 10 | + |
| 11 | +use PhpParser\Node; |
| 12 | +use PHPStan\Analyser\Scope; |
| 13 | +use PHPStan\Rules\Rule; |
| 14 | +use PHPStan\Rules\RuleErrorBuilder; |
| 15 | + |
| 16 | +/** |
| 17 | + * @implements \PHPStan\Rules\Rule<\PhpParser\Node\Stmt\ClassLike> |
| 18 | + */ |
| 19 | +final class NamingConventionRule implements Rule |
| 20 | +{ |
| 21 | + public function getNodeType(): string |
| 22 | + { |
| 23 | + return Node\Stmt\ClassLike::class; |
| 24 | + } |
| 25 | + |
| 26 | + public function processNode(Node $node, Scope $scope): array |
| 27 | + { |
| 28 | + if (!$this->isRelevantNode($node)) { |
| 29 | + return []; |
| 30 | + } |
| 31 | + |
| 32 | + if ($node->name === null) { |
| 33 | + return []; |
| 34 | + } |
| 35 | + |
| 36 | + $className = $node->name->toString(); |
| 37 | + $errors = []; |
| 38 | + |
| 39 | + if ($node instanceof Node\Stmt\Interface_ && substr($className, -9) !== 'Interface') { |
| 40 | + $errors[] = RuleErrorBuilder::message( |
| 41 | + sprintf( |
| 42 | + 'Interface "%s" should have "Interface" suffix', |
| 43 | + $className |
| 44 | + ) |
| 45 | + )->build(); |
| 46 | + } |
| 47 | + |
| 48 | + if ($node instanceof Node\Stmt\Trait_ && substr($className, -5) !== 'Trait') { |
| 49 | + $errors[] = RuleErrorBuilder::message( |
| 50 | + sprintf( |
| 51 | + 'Trait "%s" should have "Trait" suffix', |
| 52 | + $className |
| 53 | + ) |
| 54 | + )->build(); |
| 55 | + } |
| 56 | + |
| 57 | + if ($node instanceof Node\Stmt\Class_ && $node->isAbstract() && strpos($className, 'Abstract') !== 0) { |
| 58 | + $errors[] = RuleErrorBuilder::message( |
| 59 | + sprintf( |
| 60 | + 'Abstract class "%s" should have "Abstract" prefix', |
| 61 | + $className |
| 62 | + ) |
| 63 | + )->build(); |
| 64 | + } |
| 65 | + |
| 66 | + return $errors; |
| 67 | + } |
| 68 | + |
| 69 | + private function isRelevantNode(Node $node): bool |
| 70 | + { |
| 71 | + return $node instanceof Node\Stmt\Interface_ |
| 72 | + || $node instanceof Node\Stmt\Trait_ |
| 73 | + || ($node instanceof Node\Stmt\Class_ && $node->isAbstract()); |
| 74 | + } |
| 75 | +} |
0 commit comments