Skip to content

Commit 2417780

Browse files
committed
[DeadCode] Skip RemoveDeadIfBlockRector on empty if with elseif and trailing else
An empty if body followed by elseif and else was merged into "if (!cond && elseifCond) {...} else {...}". When the original if condition was true, the negated condition made the else branch run, which the empty if body never did. Keep such code unchanged. Fixes rectorphp/rector#9884 Claude-Session: https://claude.ai/code/session_01MszFhfN8nK7KR3mBjda8P2
1 parent 3bdc4c6 commit 2417780

2 files changed

Lines changed: 6 additions & 20 deletions

File tree

rules-tests/DeadCode/Rector/If_/RemoveDeadIfBlockRector/Fixture/empty_if_with_elseif_and_else.php.inc renamed to rules-tests/DeadCode/Rector/If_/RemoveDeadIfBlockRector/Fixture/skip_empty_if_with_elseif_and_else.php.inc

Lines changed: 0 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -18,23 +18,3 @@ class EmptyIfWithElseIfAndElse
1818
}
1919

2020
?>
21-
-----
22-
<?php
23-
24-
namespace Rector\Tests\DeadCode\Rector\If_\RemoveDeadIfBlockRector\Fixture;
25-
26-
class EmptyIfWithElseIfAndElse
27-
{
28-
public function calculatePrice($qty, $cond, $price1, $price2)
29-
{
30-
if ($qty >= 1 && !$cond) {
31-
$total = $qty * $price1;
32-
} else {
33-
$total = $qty * $price2;
34-
}
35-
36-
return $total;
37-
}
38-
}
39-
40-
?>

‎rules/DeadCode/Rector/If_/RemoveDeadIfBlockRector.php‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,12 @@ public function refactor(Node $node): int|null|If_
131131
// When the if body is blank but it has an elseif,
132132
// merge the negated if condition with the elseif condition
133133
if ($node->elseifs !== []) {
134+
// A trailing else would run when the negated if condition is true,
135+
// which the original empty if body never did, so keep the code as is.
136+
if ($node->else instanceof Else_) {
137+
return null;
138+
}
139+
134140
$firstElseIf = $node->elseifs[0];
135141
$cond = new BooleanAnd(
136142
$this->conditionInverter->createInvertedCondition($node->cond),

0 commit comments

Comments
 (0)