|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Rules\Constants; |
| 4 | + |
| 5 | +use Attribute; |
| 6 | +use PhpParser\Node; |
| 7 | +use PHPStan\Analyser\Scope; |
| 8 | +use PHPStan\DependencyInjection\RegisteredRule; |
| 9 | +use PHPStan\Php\PhpVersion; |
| 10 | +use PHPStan\Rules\AttributesCheck; |
| 11 | +use PHPStan\Rules\Rule; |
| 12 | +use PHPStan\Rules\RuleErrorBuilder; |
| 13 | +use const PHP_VERSION_ID; |
| 14 | + |
| 15 | +/** |
| 16 | + * @implements Rule<Node\Stmt\Const_> |
| 17 | + */ |
| 18 | +#[RegisteredRule(level: 0)] |
| 19 | +final class ConstantAttributesRule implements Rule |
| 20 | +{ |
| 21 | + |
| 22 | + public function __construct( |
| 23 | + private AttributesCheck $attributesCheck, |
| 24 | + private PhpVersion $phpVersion, |
| 25 | + ) |
| 26 | + { |
| 27 | + } |
| 28 | + |
| 29 | + public function getNodeType(): string |
| 30 | + { |
| 31 | + return Node\Stmt\Const_::class; |
| 32 | + } |
| 33 | + |
| 34 | + public function processNode(Node $node, Scope $scope): array |
| 35 | + { |
| 36 | + if ($node->attrGroups === []) { |
| 37 | + return []; |
| 38 | + } |
| 39 | + |
| 40 | + if (!$this->phpVersion->supportsAttributesOnGlobalConstants()) { |
| 41 | + return [ |
| 42 | + RuleErrorBuilder::message('Attributes on global constants are supported only on PHP 8.5 and later.') |
| 43 | + ->identifier('constant.attributesNotSupported') |
| 44 | + ->nonIgnorable() |
| 45 | + ->build(), |
| 46 | + ]; |
| 47 | + } |
| 48 | + |
| 49 | + if (PHP_VERSION_ID < 80500) { |
| 50 | + // because of Attribute::TARGET_CONSTANT constant |
| 51 | + return [ |
| 52 | + RuleErrorBuilder::message('ConstantAttributesRule requires PHP 8.5 runtime to check the code.') |
| 53 | + ->identifier('constant.attributesRuleCannotRun') |
| 54 | + ->nonIgnorable() |
| 55 | + ->build(), |
| 56 | + ]; |
| 57 | + } |
| 58 | + |
| 59 | + return $this->attributesCheck->check( |
| 60 | + $scope, |
| 61 | + $node->attrGroups, |
| 62 | + Attribute::TARGET_CONSTANT, |
| 63 | + 'constant', |
| 64 | + ); |
| 65 | + } |
| 66 | + |
| 67 | +} |
0 commit comments