|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Rector\CodeQuality\Rector\BooleanNot; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Expr\BinaryOp; |
| 9 | +use PhpParser\Node\Expr\BinaryOp\BooleanAnd; |
| 10 | +use PhpParser\Node\Expr\BooleanNot; |
| 11 | +use Rector\NodeManipulator\BinaryOpManipulator; |
| 12 | +use Rector\Rector\AbstractRector; |
| 13 | +use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; |
| 14 | +use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; |
| 15 | + |
| 16 | +/** |
| 17 | + * @see \Rector\Tests\CodeQuality\Rector\BooleanNot\NegatedAndsToOrRector\NegatedAndsToOrRectorTest |
| 18 | + */ |
| 19 | +final class NegatedAndsToOrRector extends AbstractRector |
| 20 | +{ |
| 21 | + public function __construct( |
| 22 | + private readonly BinaryOpManipulator $binaryOpManipulator |
| 23 | + ) { |
| 24 | + } |
| 25 | + |
| 26 | + public function getRuleDefinition(): RuleDefinition |
| 27 | + { |
| 28 | + return new RuleDefinition( |
| 29 | + 'Simplify negated "and" conditions to "or" with de Morgan theorem', |
| 30 | + [ |
| 31 | + new CodeSample( |
| 32 | + <<<'CODE_SAMPLE' |
| 33 | +$a = 5; |
| 34 | +$b = 10; |
| 35 | +$result = !($a > 20 && $b <= 50); |
| 36 | +CODE_SAMPLE |
| 37 | + , |
| 38 | + <<<'CODE_SAMPLE' |
| 39 | +$a = 5; |
| 40 | +$b = 10; |
| 41 | +$result = $a <= 20 || $b > 50; |
| 42 | +CODE_SAMPLE |
| 43 | + ), |
| 44 | + ] |
| 45 | + ); |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * @return array<class-string<Node>> |
| 50 | + */ |
| 51 | + public function getNodeTypes(): array |
| 52 | + { |
| 53 | + return [BooleanNot::class]; |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * @param BooleanNot $node |
| 58 | + */ |
| 59 | + public function refactor(Node $node): ?BinaryOp |
| 60 | + { |
| 61 | + if (! $node->expr instanceof BooleanAnd) { |
| 62 | + return null; |
| 63 | + } |
| 64 | + |
| 65 | + return $this->binaryOpManipulator->inverseBooleanAnd($node->expr); |
| 66 | + } |
| 67 | +} |
0 commit comments