|
5 | 5 | namespace Rector\CodeQuality\Rector\LogicalAnd; |
6 | 6 |
|
7 | 7 | use PhpParser\Node; |
| 8 | +use PhpParser\Node\Expr; |
8 | 9 | use PhpParser\Node\Expr\Assign; |
| 10 | +use PhpParser\Node\Expr\AssignOp; |
| 11 | +use PhpParser\Node\Expr\AssignRef; |
| 12 | +use PhpParser\Node\Expr\BinaryOp; |
9 | 13 | use PhpParser\Node\Expr\BinaryOp\BooleanAnd; |
10 | 14 | use PhpParser\Node\Expr\BinaryOp\BooleanOr; |
11 | 15 | use PhpParser\Node\Expr\BinaryOp\LogicalAnd; |
12 | 16 | use PhpParser\Node\Expr\BinaryOp\LogicalOr; |
| 17 | +use PhpParser\Node\Expr\BitwiseNot; |
| 18 | +use PhpParser\Node\Expr\BooleanNot; |
| 19 | +use PhpParser\Node\Expr\Cast; |
| 20 | +use PhpParser\Node\Expr\ErrorSuppress; |
| 21 | +use PhpParser\Node\Expr\UnaryMinus; |
| 22 | +use PhpParser\Node\Expr\UnaryPlus; |
| 23 | +use Rector\NodeTypeResolver\Node\AttributeKey; |
13 | 24 | use Rector\Rector\AbstractRector; |
14 | 25 | use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; |
15 | 26 | use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; |
@@ -74,10 +85,33 @@ private function refactorLogicalToBoolean(LogicalOr|LogicalAnd $node): BooleanAn |
74 | 85 | $node->right = $this->refactorLogicalToBoolean($node->right); |
75 | 86 | } |
76 | 87 |
|
| 88 | + // "and"/"or" bind looser than "="/"+="; once they become "&&"/"||" the assignment must be |
| 89 | + // re-printed so the pretty-printer re-adds the parentheses that keep the original semantics |
| 90 | + $this->reprintNestedAssign($node->left); |
| 91 | + $this->reprintNestedAssign($node->right); |
| 92 | + |
77 | 93 | if ($node instanceof LogicalOr) { |
78 | 94 | return new BooleanOr($node->left, $node->right); |
79 | 95 | } |
80 | 96 |
|
81 | 97 | return new BooleanAnd($node->left, $node->right); |
82 | 98 | } |
| 99 | + |
| 100 | + private function reprintNestedAssign(Expr $expr): void |
| 101 | + { |
| 102 | + if ($expr instanceof Assign || $expr instanceof AssignOp || $expr instanceof AssignRef) { |
| 103 | + $expr->setAttribute(AttributeKey::ORIGINAL_NODE, null); |
| 104 | + return; |
| 105 | + } |
| 106 | + |
| 107 | + if ($expr instanceof BooleanNot || $expr instanceof BitwiseNot || $expr instanceof UnaryMinus || $expr instanceof UnaryPlus || $expr instanceof ErrorSuppress || $expr instanceof Cast) { |
| 108 | + $this->reprintNestedAssign($expr->expr); |
| 109 | + return; |
| 110 | + } |
| 111 | + |
| 112 | + if ($expr instanceof BinaryOp) { |
| 113 | + $this->reprintNestedAssign($expr->left); |
| 114 | + $this->reprintNestedAssign($expr->right); |
| 115 | + } |
| 116 | + } |
83 | 117 | } |
0 commit comments