|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Rules\Functions; |
| 4 | + |
| 5 | +use PhpParser\Node; |
| 6 | +use PhpParser\Node\Expr\FuncCall; |
| 7 | +use PHPStan\Analyser\Scope; |
| 8 | +use PHPStan\Reflection\ReflectionProvider; |
| 9 | +use PHPStan\Rules\Rule; |
| 10 | +use PHPStan\Rules\RuleErrorBuilder; |
| 11 | +use PHPStan\Type\StaticTypeFactory; |
| 12 | +use PHPStan\Type\VerbosityLevel; |
| 13 | +use function count; |
| 14 | +use function sprintf; |
| 15 | +use function strtolower; |
| 16 | + |
| 17 | +/** |
| 18 | + * @implements Rule<Node\Expr\FuncCall> |
| 19 | + */ |
| 20 | +class ArrayFilterRule implements Rule |
| 21 | +{ |
| 22 | + |
| 23 | + public function __construct(private ReflectionProvider $reflectionProvider) |
| 24 | + { |
| 25 | + } |
| 26 | + |
| 27 | + public function getNodeType(): string |
| 28 | + { |
| 29 | + return FuncCall::class; |
| 30 | + } |
| 31 | + |
| 32 | + public function processNode(Node $node, Scope $scope): array |
| 33 | + { |
| 34 | + if (!($node->name instanceof Node\Name)) { |
| 35 | + return []; |
| 36 | + } |
| 37 | + |
| 38 | + $functionName = $this->reflectionProvider->resolveFunctionName($node->name, $scope); |
| 39 | + |
| 40 | + if ($functionName === null || strtolower($functionName) !== 'array_filter') { |
| 41 | + return []; |
| 42 | + } |
| 43 | + |
| 44 | + $args = $node->getArgs(); |
| 45 | + if (count($args) !== 1) { |
| 46 | + return []; |
| 47 | + } |
| 48 | + |
| 49 | + $arrayType = $scope->getType($args[0]->value); |
| 50 | + |
| 51 | + if ($arrayType->isIterableAtLeastOnce()->no()) { |
| 52 | + $message = 'Parameter #1 $array (%s) to function array_filter is empty, call has no effect.'; |
| 53 | + return [ |
| 54 | + RuleErrorBuilder::message(sprintf( |
| 55 | + $message, |
| 56 | + $arrayType->describe(VerbosityLevel::value()), |
| 57 | + ))->build(), |
| 58 | + ]; |
| 59 | + } |
| 60 | + |
| 61 | + $falsyType = StaticTypeFactory::falsey(); |
| 62 | + $isSuperType = $falsyType->isSuperTypeOf($arrayType->getIterableValueType()); |
| 63 | + |
| 64 | + if ($isSuperType->no()) { |
| 65 | + $message = 'Parameter #1 $array (%s) to function array_filter does not contain falsy values, the array will always stay the same.'; |
| 66 | + return [ |
| 67 | + RuleErrorBuilder::message(sprintf( |
| 68 | + $message, |
| 69 | + $arrayType->describe(VerbosityLevel::value()), |
| 70 | + ))->build(), |
| 71 | + ]; |
| 72 | + } |
| 73 | + |
| 74 | + if ($isSuperType->yes()) { |
| 75 | + $message = 'Parameter #1 $array (%s) to function array_filter contains falsy values only, the result will always be an empty array.'; |
| 76 | + return [ |
| 77 | + RuleErrorBuilder::message(sprintf( |
| 78 | + $message, |
| 79 | + $arrayType->describe(VerbosityLevel::value()), |
| 80 | + ))->build(), |
| 81 | + ]; |
| 82 | + } |
| 83 | + |
| 84 | + return []; |
| 85 | + } |
| 86 | + |
| 87 | +} |
0 commit comments