|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Rules\PHPUnit; |
| 4 | + |
| 5 | +use PhpParser\Node; |
| 6 | +use PhpParser\Node\Expr\CallLike; |
| 7 | +use PhpParser\Node\Expr\FuncCall; |
| 8 | +use PhpParser\Node\Expr\MethodCall; |
| 9 | +use PhpParser\Node\Expr\StaticCall; |
| 10 | +use PhpParser\Node\Identifier; |
| 11 | +use PhpParser\Node\Name; |
| 12 | +use PHPStan\Analyser\Scope; |
| 13 | +use PHPStan\Rules\Rule; |
| 14 | +use PHPStan\Rules\RuleErrorBuilder; |
| 15 | +use function count; |
| 16 | +use function in_array; |
| 17 | +use function sprintf; |
| 18 | +use function strtolower; |
| 19 | + |
| 20 | +/** |
| 21 | + * @implements Rule<CallLike> |
| 22 | + */ |
| 23 | +class AssertEmptyIsDiscouragedRule implements Rule |
| 24 | +{ |
| 25 | + |
| 26 | + public function getNodeType(): string |
| 27 | + { |
| 28 | + return CallLike::class; |
| 29 | + } |
| 30 | + |
| 31 | + public function processNode(Node $node, Scope $scope): array |
| 32 | + { |
| 33 | + if ($node->isFirstClassCallable() || count($node->getArgs()) < 1) { |
| 34 | + return []; |
| 35 | + } |
| 36 | + |
| 37 | + if ($node instanceof MethodCall || $node instanceof StaticCall) { |
| 38 | + if (!$node->name instanceof Identifier || !in_array($node->name->toLowerString(), ['assertempty', 'assertnotempty'], true)) { |
| 39 | + return []; |
| 40 | + } |
| 41 | + if (!AssertRuleHelper::isMethodOrStaticCallOnAssert($node, $scope)) { |
| 42 | + return []; |
| 43 | + } |
| 44 | + } elseif ($node instanceof FuncCall) { |
| 45 | + if (!$node->name instanceof Name || !in_array(strtolower($scope->resolveName($node->name)), ['phpunit\\framework\\assertempty', 'phpunit\\framework\\assertnotempty'], true)) { |
| 46 | + return []; |
| 47 | + } |
| 48 | + } else { |
| 49 | + return []; |
| 50 | + } |
| 51 | + |
| 52 | + return [ |
| 53 | + RuleErrorBuilder::message(sprintf( |
| 54 | + '%s() is not allowed. Use more strict assertion.', |
| 55 | + $node instanceof FuncCall ? $node->name->getLast() : $node->name->toString(), |
| 56 | + )) |
| 57 | + ->identifier('empty.notAllowed') |
| 58 | + ->build(), |
| 59 | + ]; |
| 60 | + } |
| 61 | + |
| 62 | +} |
0 commit comments