|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Symplify\PHPStanRules\Rules\Complexity; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Expr\Array_; |
| 9 | +use PhpParser\Node\Expr\FuncCall; |
| 10 | +use PhpParser\Node\Name; |
| 11 | +use PHPStan\Analyser\Scope; |
| 12 | +use PHPStan\Rules\Rule; |
| 13 | +use PHPStan\Rules\RuleError; |
| 14 | +use PHPStan\Rules\RuleErrorBuilder; |
| 15 | +use Symplify\PHPStanRules\Enum\RuleIdentifier; |
| 16 | + |
| 17 | +/** |
| 18 | + * @implements Rule<FuncCall> |
| 19 | + * |
| 20 | + * @see \Symplify\PHPStanRules\Tests\Rules\NoArrayMapWithArrayCallableRule\NoArrayMapWithArrayCallableRuleTest |
| 21 | + */ |
| 22 | +final class NoArrayMapWithArrayCallableRule implements Rule |
| 23 | +{ |
| 24 | + /** |
| 25 | + * @var string |
| 26 | + */ |
| 27 | + public const ERROR_MESSAGE = 'Avoid using array callables in array_map(), as it cripples static analysis on used method'; |
| 28 | + |
| 29 | + public function getNodeType(): string |
| 30 | + { |
| 31 | + return FuncCall::class; |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * @param FuncCall $node |
| 36 | + * @return RuleError[] |
| 37 | + */ |
| 38 | + public function processNode(Node $node, Scope $scope): array |
| 39 | + { |
| 40 | + if (! $node->name instanceof Name) { |
| 41 | + return []; |
| 42 | + } |
| 43 | + |
| 44 | + $functionName = $node->name->toString(); |
| 45 | + if ($functionName !== 'array_map') { |
| 46 | + return []; |
| 47 | + } |
| 48 | + |
| 49 | + if ($node->isFirstClassCallable()) { |
| 50 | + return []; |
| 51 | + } |
| 52 | + |
| 53 | + $args = $node->getArgs(); |
| 54 | + $firstArgValue = $args[0]->value; |
| 55 | + if (! $firstArgValue instanceof Array_) { |
| 56 | + return []; |
| 57 | + } |
| 58 | + |
| 59 | + $identifierRuleError = RuleErrorBuilder::message(self::ERROR_MESSAGE) |
| 60 | + ->identifier(RuleIdentifier::NO_ARRAY_MAP_WITH_ARRAY_CALLABLE) |
| 61 | + ->build(); |
| 62 | + |
| 63 | + return [$identifierRuleError]; |
| 64 | + } |
| 65 | +} |
0 commit comments