|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <[email protected]> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\AI\PHPStan; |
| 13 | + |
| 14 | +use PhpParser\Node; |
| 15 | +use PhpParser\Node\Expr\FuncCall; |
| 16 | +use PHPStan\Analyser\Scope; |
| 17 | +use PHPStan\Rules\Rule; |
| 18 | +use PHPStan\Rules\RuleErrorBuilder; |
| 19 | + |
| 20 | +/** |
| 21 | + * PHPStan rule that forbids usage of empty() function. |
| 22 | + * |
| 23 | + * This rule enforces that empty() should not be used in favor of explicit checks |
| 24 | + * like null checks, count() for arrays, or string length checks. |
| 25 | + * |
| 26 | + * @author Oskar Stark <[email protected]> |
| 27 | + * |
| 28 | + * @implements Rule<FuncCall> |
| 29 | + */ |
| 30 | +final class ForbidEmptyRule implements Rule |
| 31 | +{ |
| 32 | + public function getNodeType(): string |
| 33 | + { |
| 34 | + return FuncCall::class; |
| 35 | + } |
| 36 | + |
| 37 | + public function processNode(Node $node, Scope $scope): array |
| 38 | + { |
| 39 | + if (!$node instanceof FuncCall) { |
| 40 | + return []; |
| 41 | + } |
| 42 | + |
| 43 | + if (!$node->name instanceof Node\Name) { |
| 44 | + return []; |
| 45 | + } |
| 46 | + |
| 47 | + $functionName = $node->name->toString(); |
| 48 | + |
| 49 | + if ('empty' !== strtolower($functionName)) { |
| 50 | + return []; |
| 51 | + } |
| 52 | + |
| 53 | + // Allow empty() in ai-bundle config file where validation logic can be complex |
| 54 | + if (str_ends_with($scope->getFile(), 'ai-bundle/config/options.php')) { |
| 55 | + return []; |
| 56 | + } |
| 57 | + |
| 58 | + return [ |
| 59 | + RuleErrorBuilder::message( |
| 60 | + 'Usage of empty() function is forbidden. Use explicit checks instead: null check, count() for arrays, or string length checks.' |
| 61 | + ) |
| 62 | + ->line($node->getLine()) |
| 63 | + ->identifier('symfonyAi.forbidEmpty') |
| 64 | + ->tip('Replace empty() with explicit checks like $var !== null && $var !== \'\' for strings, count($var) > 0 for arrays, etc.') |
| 65 | + ->build(), |
| 66 | + ]; |
| 67 | + } |
| 68 | +} |
0 commit comments