|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace BenSampo\Enum\PHPStan; |
| 4 | + |
| 5 | +use BenSampo\Enum\Enum; |
| 6 | +use PhpParser\Node; |
| 7 | +use PHPStan\Analyser\Scope; |
| 8 | +use PHPStan\Node\InClassNode; |
| 9 | +use PHPStan\Rules\Rule; |
| 10 | +use PHPStan\Rules\RuleErrorBuilder; |
| 11 | + |
| 12 | +/** @implements Rule<InClassNode> */ |
| 13 | +final class UniqueValuesRule implements Rule |
| 14 | +{ |
| 15 | + public function getNodeType(): string |
| 16 | + { |
| 17 | + return InClassNode::class; |
| 18 | + } |
| 19 | + |
| 20 | + public function processNode(Node $node, Scope $scope): array |
| 21 | + { |
| 22 | + assert($node instanceof InClassNode); |
| 23 | + |
| 24 | + $reflection = $node->getClassReflection(); |
| 25 | + if (! $reflection->isSubclassOf(Enum::class)) { |
| 26 | + return []; |
| 27 | + } |
| 28 | + |
| 29 | + $constants = []; |
| 30 | + foreach ($reflection->getNativeReflection()->getReflectionConstants() as $constant) { |
| 31 | + $constants[$constant->name] = $constant->getValue(); |
| 32 | + } |
| 33 | + |
| 34 | + $duplicateConstants = []; |
| 35 | + foreach ($constants as $name => $value) { |
| 36 | + $constantsWithValue = array_filter($constants, fn (mixed $v): bool => $v === $value); |
| 37 | + if (count($constantsWithValue) > 1) { |
| 38 | + $duplicateConstants []= array_keys($constantsWithValue); |
| 39 | + } |
| 40 | + } |
| 41 | + $duplicateConstants = array_unique($duplicateConstants); |
| 42 | + |
| 43 | + if (count($duplicateConstants) > 0) { |
| 44 | + $fqcn = $reflection->getName(); |
| 45 | + $constantsString = json_encode($duplicateConstants); |
| 46 | + |
| 47 | + return [ |
| 48 | + RuleErrorBuilder::message("Enum class {$fqcn} contains constants with duplicate values: {$constantsString}.") |
| 49 | + ->build(), |
| 50 | + ]; |
| 51 | + } |
| 52 | + |
| 53 | + return []; |
| 54 | + } |
| 55 | +} |
0 commit comments