|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Symplify\PHPStanRules\Rules\Symfony; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Attribute; |
| 9 | +use PhpParser\Node\Scalar\String_; |
| 10 | +use PHPStan\Analyser\Scope; |
| 11 | +use PHPStan\Rules\Rule; |
| 12 | +use PHPStan\Rules\RuleErrorBuilder; |
| 13 | +use Symplify\PHPStanRules\Enum\RuleIdentifier\SymfonyRuleIdentifier; |
| 14 | +use Symplify\PHPStanRules\Enum\SensioClass; |
| 15 | +use Symplify\PHPStanRules\Enum\SymfonyClass; |
| 16 | + |
| 17 | +/** |
| 18 | + * @see \Symplify\PHPStanRules\Tests\Rules\Symfony\RequireIsGrantedEnumRule\RequireIsGrantedEnumRuleTest |
| 19 | + * |
| 20 | + * @implements Rule<Attribute> |
| 21 | + */ |
| 22 | +final class RequireIsGrantedEnumRule implements Rule |
| 23 | +{ |
| 24 | + public const ERROR_MESSAGE = 'Instead of "%s" string, use enum constant for #[IsGranted]'; |
| 25 | + |
| 26 | + public function getNodeType(): string |
| 27 | + { |
| 28 | + return Attribute::class; |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * @param Attribute $node |
| 33 | + */ |
| 34 | + public function processNode(Node $node, Scope $scope): array |
| 35 | + { |
| 36 | + if (! in_array($node->name->toString(), [SensioClass::IS_GRANTED, SymfonyClass::IS_GRANTED], true)) { |
| 37 | + return []; |
| 38 | + } |
| 39 | + |
| 40 | + $isGrantedExpr = $node->args[0]->value; |
| 41 | + if (! $isGrantedExpr instanceof String_) { |
| 42 | + return []; |
| 43 | + } |
| 44 | + |
| 45 | + $identifierRuleError = RuleErrorBuilder::message(sprintf(self::ERROR_MESSAGE, $isGrantedExpr->value)) |
| 46 | + ->identifier(SymfonyRuleIdentifier::REQUIRED_IS_GRANTED_ENUM) |
| 47 | + ->build(); |
| 48 | + |
| 49 | + return [$identifierRuleError]; |
| 50 | + } |
| 51 | +} |
0 commit comments