| 
 | 1 | +<?php declare(strict_types = 1);  | 
 | 2 | + | 
 | 3 | +namespace PHPStan\Rules\Operators;  | 
 | 4 | + | 
 | 5 | +use PhpParser\Node;  | 
 | 6 | +use PhpParser\Node\Expr\BinaryOp;  | 
 | 7 | +use PHPStan\Analyser\Scope;  | 
 | 8 | +use PHPStan\Rules\Rule;  | 
 | 9 | +use PHPStan\Type\FloatType;  | 
 | 10 | + | 
 | 11 | +class OperandsInComparisonRule implements Rule  | 
 | 12 | +{  | 
 | 13 | + | 
 | 14 | +	public function getNodeType(): string  | 
 | 15 | +	{  | 
 | 16 | +		return BinaryOp::class;  | 
 | 17 | +	}  | 
 | 18 | + | 
 | 19 | +	/**  | 
 | 20 | +	 * @param Node $node  | 
 | 21 | +	 * @param Scope $scope  | 
 | 22 | +	 * @return string[]  | 
 | 23 | +	 */  | 
 | 24 | +	public function processNode(Node $node, Scope $scope): array  | 
 | 25 | +	{  | 
 | 26 | +		if (!$node instanceof BinaryOp\Equal  | 
 | 27 | +			&& !$node instanceof BinaryOp\Identical  | 
 | 28 | +			&& !$node instanceof BinaryOp\NotEqual  | 
 | 29 | +			&& !$node instanceof BinaryOp\NotIdentical  | 
 | 30 | +			&& !$node instanceof BinaryOp\GreaterOrEqual  | 
 | 31 | +			&& !$node instanceof BinaryOp\SmallerOrEqual  | 
 | 32 | +		) {  | 
 | 33 | +			return [];  | 
 | 34 | +		}  | 
 | 35 | + | 
 | 36 | +		$rightType = $scope->getType($node->right);  | 
 | 37 | +		$leftType = $scope->getType($node->left);  | 
 | 38 | + | 
 | 39 | +		if ($rightType instanceof FloatType || $leftType instanceof FloatType) {  | 
 | 40 | +			if ($node instanceof  BinaryOp\Equal || $node instanceof BinaryOp\Identical) {  | 
 | 41 | +				return [  | 
 | 42 | +					'Exact comparison of floating-point numbers is not accurate.' . PHP_EOL  | 
 | 43 | +					. 'You should use `abs($left - $right) < $epsilon`, where $epsilon is maximum allowed deviation.',  | 
 | 44 | +				];  | 
 | 45 | +			}  | 
 | 46 | + | 
 | 47 | +			if ($node instanceof  BinaryOp\NotEqual || $node instanceof BinaryOp\NotIdentical) {  | 
 | 48 | +				return [  | 
 | 49 | +					'Exact comparison of floating-point numbers is not accurate.' . PHP_EOL  | 
 | 50 | +					. 'You should use `abs($left - $right) >= $epsilon`, where $epsilon is maximum allowed deviation.',  | 
 | 51 | +				];  | 
 | 52 | +			}  | 
 | 53 | + | 
 | 54 | +			if ($node instanceof BinaryOp\GreaterOrEqual) {  | 
 | 55 | +				return [  | 
 | 56 | +					'Exact comparison of floating-point numbers is not accurate.' . PHP_EOL  | 
 | 57 | +					. 'You should use `$left - $right >= $epsilon`, where $epsilon is maximum allowed deviation.',  | 
 | 58 | +				];  | 
 | 59 | +			}  | 
 | 60 | +			if ($node instanceof BinaryOp\SmallerOrEqual) {  | 
 | 61 | +				return [  | 
 | 62 | +					'Exact comparison of floating-point numbers is not accurate.' . PHP_EOL  | 
 | 63 | +					. 'You should use `$right - $left >= $epsilon`, where $epsilon is maximum allowed deviation.',  | 
 | 64 | +				];  | 
 | 65 | +			}  | 
 | 66 | +		}  | 
 | 67 | + | 
 | 68 | +		return [];  | 
 | 69 | +	}  | 
 | 70 | + | 
 | 71 | +}  | 
0 commit comments