From 2417780e33eaee6b65ba36d1515fe6c4db9876ea Mon Sep 17 00:00:00 2001 From: Tomas Votruba Date: Thu, 3 Sep 2026 21:45:06 +0200 Subject: [PATCH] [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 --- ...kip_empty_if_with_elseif_and_else.php.inc} | 20 ------------------- .../Rector/If_/RemoveDeadIfBlockRector.php | 6 ++++++ 2 files changed, 6 insertions(+), 20 deletions(-) rename rules-tests/DeadCode/Rector/If_/RemoveDeadIfBlockRector/Fixture/{empty_if_with_elseif_and_else.php.inc => skip_empty_if_with_elseif_and_else.php.inc} (50%) diff --git a/rules-tests/DeadCode/Rector/If_/RemoveDeadIfBlockRector/Fixture/empty_if_with_elseif_and_else.php.inc b/rules-tests/DeadCode/Rector/If_/RemoveDeadIfBlockRector/Fixture/skip_empty_if_with_elseif_and_else.php.inc similarity index 50% rename from rules-tests/DeadCode/Rector/If_/RemoveDeadIfBlockRector/Fixture/empty_if_with_elseif_and_else.php.inc rename to rules-tests/DeadCode/Rector/If_/RemoveDeadIfBlockRector/Fixture/skip_empty_if_with_elseif_and_else.php.inc index 4915bc7e364..2e1db5888c9 100644 --- a/rules-tests/DeadCode/Rector/If_/RemoveDeadIfBlockRector/Fixture/empty_if_with_elseif_and_else.php.inc +++ b/rules-tests/DeadCode/Rector/If_/RemoveDeadIfBlockRector/Fixture/skip_empty_if_with_elseif_and_else.php.inc @@ -18,23 +18,3 @@ class EmptyIfWithElseIfAndElse } ?> ------ -= 1 && !$cond) { - $total = $qty * $price1; - } else { - $total = $qty * $price2; - } - - return $total; - } -} - -?> diff --git a/rules/DeadCode/Rector/If_/RemoveDeadIfBlockRector.php b/rules/DeadCode/Rector/If_/RemoveDeadIfBlockRector.php index b5bea0b2e3d..3db4d419c37 100644 --- a/rules/DeadCode/Rector/If_/RemoveDeadIfBlockRector.php +++ b/rules/DeadCode/Rector/If_/RemoveDeadIfBlockRector.php @@ -131,6 +131,12 @@ public function refactor(Node $node): int|null|If_ // When the if body is blank but it has an elseif, // merge the negated if condition with the elseif condition if ($node->elseifs !== []) { + // A trailing else would run when the negated if condition is true, + // which the original empty if body never did, so keep the code as is. + if ($node->else instanceof Else_) { + return null; + } + $firstElseIf = $node->elseifs[0]; $cond = new BooleanAnd( $this->conditionInverter->createInvertedCondition($node->cond),