|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Sourceability\PHPStan\Rules; |
| 4 | + |
| 5 | +use PhpParser\Node; |
| 6 | +use PhpParser\Node\Expr\BinaryOp; |
| 7 | +use PhpParser\Node\Expr\BinaryOp\NotIdentical; |
| 8 | +use PHPStan\Analyser\Scope; |
| 9 | +use PHPStan\Rules\BooleansInConditions\BooleanRuleHelper; |
| 10 | +use PHPStan\Rules\Rule; |
| 11 | + |
| 12 | +class ConstantBooleanNotIdenticalRule implements Rule |
| 13 | +{ |
| 14 | + /** |
| 15 | + * @var ConstantBooleanRuleHelper |
| 16 | + */ |
| 17 | + private $constantBooleanRuleHelper; |
| 18 | + |
| 19 | + /** |
| 20 | + * @var BooleanRuleHelper |
| 21 | + */ |
| 22 | + private $booleanRuleHelper; |
| 23 | + |
| 24 | + public function __construct( |
| 25 | + ConstantBooleanRuleHelper $constantBooleanRuleHelper, |
| 26 | + BooleanRuleHelper $booleanRuleHelper |
| 27 | + ) { |
| 28 | + $this->constantBooleanRuleHelper = $constantBooleanRuleHelper; |
| 29 | + $this->booleanRuleHelper = $booleanRuleHelper; |
| 30 | + } |
| 31 | + |
| 32 | + public function getNodeType(): string |
| 33 | + { |
| 34 | + return NotIdentical::class; |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * @return string[] errors |
| 39 | + */ |
| 40 | + public function processNode(Node $node, Scope $scope): array |
| 41 | + { |
| 42 | + if (!$node instanceof BinaryOp) { |
| 43 | + return []; |
| 44 | + } |
| 45 | + |
| 46 | + $constantBooleanTypeLeft = $this->constantBooleanRuleHelper->getNonMixedConstantBooleanType( |
| 47 | + $scope, |
| 48 | + $node->left |
| 49 | + ); |
| 50 | + $constantBooleanTypeRight = $this->constantBooleanRuleHelper->getNonMixedConstantBooleanType( |
| 51 | + $scope, |
| 52 | + $node->right |
| 53 | + ); |
| 54 | + |
| 55 | + if (null === $constantBooleanTypeLeft |
| 56 | + && null === $constantBooleanTypeRight |
| 57 | + ) { |
| 58 | + return []; |
| 59 | + } |
| 60 | + |
| 61 | + if (null !== $constantBooleanTypeLeft |
| 62 | + && null !== $constantBooleanTypeRight |
| 63 | + ) { |
| 64 | + return []; |
| 65 | + } |
| 66 | + |
| 67 | + if (null !== $constantBooleanTypeLeft) { |
| 68 | + if ($this->booleanRuleHelper->passesAsBoolean($scope, $node->right)) { |
| 69 | + if ($constantBooleanTypeLeft->getValue()) { |
| 70 | + return ['Replace true !== $boolean with !$boolean']; |
| 71 | + } |
| 72 | + |
| 73 | + return ['Replace false !== $boolean with $boolean']; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + if (null !== $constantBooleanTypeRight) { |
| 78 | + if ($this->booleanRuleHelper->passesAsBoolean($scope, $node->right)) { |
| 79 | + if ($constantBooleanTypeRight->getValue()) { |
| 80 | + return ['Replace $boolean !== true with !$boolean']; |
| 81 | + } |
| 82 | + |
| 83 | + return ['Replace $boolean !== false with $boolean']; |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + return []; |
| 88 | + } |
| 89 | +} |
0 commit comments