|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Symplify\PHPStanRules\Rules\Rector; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Identifier; |
| 9 | +use PhpParser\Node\Stmt\ClassMethod; |
| 10 | +use PhpParser\Node\UnionType; |
| 11 | +use PHPStan\Analyser\Scope; |
| 12 | +use PHPStan\Rules\Rule; |
| 13 | +use PHPStan\Rules\RuleErrorBuilder; |
| 14 | +use Symplify\PHPStanRules\Enum\RuleIdentifier\RectorRuleIdentifier; |
| 15 | + |
| 16 | +/** |
| 17 | + * @see \Symplify\PHPStanRules\Tests\Rules\Rector\NoIntegerRefactorReturnRule\NoIntegerRefactorReturnRuleTest |
| 18 | + * |
| 19 | + * @implements Rule<ClassMethod> |
| 20 | + */ |
| 21 | +final class NoIntegerRefactorReturnRule implements Rule |
| 22 | +{ |
| 23 | + /** |
| 24 | + * @var string |
| 25 | + */ |
| 26 | + public const ERROR_MESSAGE = 'Instead of using int in refactor(), make use of attributes and return always node or a null. Using traverser enums might lead to unexpected results'; |
| 27 | + |
| 28 | + public function getNodeType(): string |
| 29 | + { |
| 30 | + return ClassMethod::class; |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * @param ClassMethod $node |
| 35 | + */ |
| 36 | + public function processNode(Node $node, Scope $scope): array |
| 37 | + { |
| 38 | + if (! $node->isPublic()) { |
| 39 | + return []; |
| 40 | + } |
| 41 | + |
| 42 | + if ($node->name->toString() !== 'refactor') { |
| 43 | + return []; |
| 44 | + } |
| 45 | + |
| 46 | + if (! $node->returnType instanceof UnionType) { |
| 47 | + return []; |
| 48 | + } |
| 49 | + |
| 50 | + foreach ($node->returnType->types as $type) { |
| 51 | + if (! $type instanceof Identifier) { |
| 52 | + continue; |
| 53 | + } |
| 54 | + |
| 55 | + if ($type->name === 'int') { |
| 56 | + $ruleError = RuleErrorBuilder::message(self::ERROR_MESSAGE) |
| 57 | + ->identifier(RectorRuleIdentifier::NO_INTEGER_REFACTOR_RETURN) |
| 58 | + ->build(); |
| 59 | + |
| 60 | + return [$ruleError]; |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return []; |
| 65 | + } |
| 66 | +} |
0 commit comments