Skip to content

Commit 647f476

Browse files
authored
[CodeQuality] Keep parentheses around Ternary operand in SimplifyConditionsRector (#8122)
Fixes #8121 - inverting a binary op whose operand is a ternary dropped the parentheses, changing evaluation due to lower ternary precedence.
1 parent fad4926 commit 647f476

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
3+
function keepParentheses()
4+
{
5+
if (! (1 < (1 ? 2 : 1))) {
6+
}
7+
}
8+
9+
?>
10+
-----
11+
<?php
12+
13+
function keepParentheses()
14+
{
15+
if (1 >= (1 ? 2 : 1)) {
16+
}
17+
}
18+
19+
?>

‎rules/CodeQuality/Rector/Identical/SimplifyConditionsRector.php‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@
1111
use PhpParser\Node\Expr\BinaryOp\Identical;
1212
use PhpParser\Node\Expr\BinaryOp\NotIdentical;
1313
use PhpParser\Node\Expr\BooleanNot;
14+
use PhpParser\Node\Expr\Ternary;
1415
use Rector\NodeManipulator\BinaryOpManipulator;
16+
use Rector\NodeTypeResolver\Node\AttributeKey;
1517
use Rector\Php71\ValueObject\TwoNodeMatch;
1618
use Rector\PhpParser\Node\AssignAndBinaryMap;
1719
use Rector\PhpParser\Node\Value\ValueResolver;
@@ -118,6 +120,14 @@ private function createInversedBooleanOp(BinaryOp $binaryOp): ?BinaryOp
118120
return null;
119121
}
120122

123+
if ($binaryOp->left instanceof Ternary) {
124+
$binaryOp->left->setAttribute(AttributeKey::WRAPPED_IN_PARENTHESES, true);
125+
}
126+
127+
if ($binaryOp->right instanceof Ternary) {
128+
$binaryOp->right->setAttribute(AttributeKey::WRAPPED_IN_PARENTHESES, true);
129+
}
130+
121131
return new $inversedBinaryClass($binaryOp->left, $binaryOp->right);
122132
}
123133
}

0 commit comments

Comments
 (0)