|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Rules\Comparison; |
| 4 | + |
| 5 | +use PhpParser\Node; |
| 6 | +use PHPStan\Analyser\Scope; |
| 7 | +use PHPStan\Rules\Rule; |
| 8 | +use PHPStan\Rules\RuleErrorBuilder; |
| 9 | +use PHPStan\Type\Constant\ConstantBooleanType; |
| 10 | +use PHPStan\Type\VerbosityLevel; |
| 11 | +use function sprintf; |
| 12 | + |
| 13 | +/** |
| 14 | + * @implements Rule<Node\Expr\BinaryOp> |
| 15 | + */ |
| 16 | +class ConstantLooseComparisonRule implements Rule |
| 17 | +{ |
| 18 | + |
| 19 | + public function __construct(private bool $checkAlwaysTrueLooseComparison) |
| 20 | + { |
| 21 | + } |
| 22 | + |
| 23 | + public function getNodeType(): string |
| 24 | + { |
| 25 | + return Node\Expr\BinaryOp::class; |
| 26 | + } |
| 27 | + |
| 28 | + public function processNode(Node $node, Scope $scope): array |
| 29 | + { |
| 30 | + if (!$node instanceof Node\Expr\BinaryOp\Equal && !$node instanceof Node\Expr\BinaryOp\NotEqual) { |
| 31 | + return []; |
| 32 | + } |
| 33 | + |
| 34 | + $nodeType = $scope->getType($node); |
| 35 | + if (!$nodeType instanceof ConstantBooleanType) { |
| 36 | + return []; |
| 37 | + } |
| 38 | + |
| 39 | + $leftType = $scope->getType($node->left); |
| 40 | + $rightType = $scope->getType($node->right); |
| 41 | + |
| 42 | + if (!$nodeType->getValue()) { |
| 43 | + return [ |
| 44 | + RuleErrorBuilder::message(sprintf( |
| 45 | + 'Loose comparison using %s between %s and %s will always evaluate to false.', |
| 46 | + $node instanceof Node\Expr\BinaryOp\Equal ? '==' : '!=', |
| 47 | + $leftType->describe(VerbosityLevel::value()), |
| 48 | + $rightType->describe(VerbosityLevel::value()), |
| 49 | + ))->build(), |
| 50 | + ]; |
| 51 | + } elseif ($this->checkAlwaysTrueLooseComparison) { |
| 52 | + return [ |
| 53 | + RuleErrorBuilder::message(sprintf( |
| 54 | + 'Loose comparison using %s between %s and %s will always evaluate to true.', |
| 55 | + $node instanceof Node\Expr\BinaryOp\Equal ? '==' : '!=', |
| 56 | + $leftType->describe(VerbosityLevel::value()), |
| 57 | + $rightType->describe(VerbosityLevel::value()), |
| 58 | + ))->build(), |
| 59 | + ]; |
| 60 | + } |
| 61 | + |
| 62 | + return []; |
| 63 | + } |
| 64 | + |
| 65 | +} |
0 commit comments