|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Xact\PHPStan\Rules; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PHPStan\Analyser\Scope; |
| 9 | +use PHPStan\Node\CollectedDataNode; |
| 10 | +use PHPStan\Rules\Rule; |
| 11 | +use PHPStan\Rules\RuleErrorBuilder; |
| 12 | +use PHPStan\Rules\Traits\TraitDeclarationCollector; |
| 13 | +use PHPStan\Rules\Traits\TraitUseCollector; |
| 14 | +use Xact\PHPStan\Exception\InvalidNodeTypeException; |
| 15 | + |
| 16 | +class UnusedTraitRule implements Rule |
| 17 | +{ |
| 18 | + /** |
| 19 | + * @inheritDoc |
| 20 | + */ |
| 21 | + public function getNodeType(): string |
| 22 | + { |
| 23 | + return CollectedDataNode::class; |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * @inheritDoc |
| 28 | + */ |
| 29 | + // phpcs:ignore SlevomatCodingStandard.Functions.UnusedParameter.UnusedParameter |
| 30 | + public function processNode(Node $node, Scope $scope): array |
| 31 | + { |
| 32 | + if (!$node instanceof CollectedDataNode) { |
| 33 | + throw InvalidNodeTypeException::create($node, CollectedDataNode::class); |
| 34 | + } |
| 35 | + |
| 36 | + $traitDeclarationData = $node->get(TraitDeclarationCollector::class); |
| 37 | + $traitUses = $node->get(TraitUseCollector::class); |
| 38 | + |
| 39 | + $usedTraits = []; |
| 40 | + foreach ($traitUses as $fileUses) { |
| 41 | + foreach ((array)$fileUses as $traitUse) { |
| 42 | + foreach ((array)$traitUse as $trait) { |
| 43 | + $usedTraits[$trait] = $trait; |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + $errors = []; |
| 49 | + foreach ($traitDeclarationData as $file => $declarations) { |
| 50 | + /** |
| 51 | + * @var string $className |
| 52 | + * @var int $line |
| 53 | + */ |
| 54 | + foreach ($declarations as [$className, $line]) { |
| 55 | + if (!array_key_exists($className, $usedTraits)) { |
| 56 | + $errors[] = RuleErrorBuilder::message("Trait {$className} is never used.") |
| 57 | + ->file($file) |
| 58 | + ->line($line) |
| 59 | + ->build(); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return $errors; |
| 65 | + } |
| 66 | +} |
0 commit comments