Skip to content

[DeadCode] Add RemoveOverriddenAssignBeforeIfElseRector - #8505

Merged
TomasVotruba merged 2 commits into
mainfrom
tv-dead-code-overridden-assign-before-if-else
Sep 17, 2026
Merged

TomasVotruba merged 2 commits into
mainfrom
tv-dead-code-overridden-assign-before-if-else

Conversation

@TomasVotruba

Copy link
Copy Markdown
Member

Adds a dead-code rule that removes an assignment placed right before an if/else when both branches fully override the same variable before reading it - so the initial value is never used.

 $result = [];
 if ($value) {
     $result = [1, 2, 3];
 } else {
     $result = [4, 5, 6];
 }

 return $result;

becomes:

 if ($value) {
     $result = [1, 2, 3];
 } else {
     $result = [4, 5, 6];
 }

 return $result;

Guards, to stay safe:

  • requires a real else (no elseif chain, no missing else)
  • skips when the initial assigned value has a side effect (e.g. a method call)
  • skips when the if condition reads the variable
  • each branch must fully override the variable in its first statement that touches it - a partial write ($result[] = ...) or a self-read ($result = array_merge($result, ...)) is left alone
  • skips static/global/by-ref variables

@TomasVotruba
TomasVotruba merged commit 0639221 into main Sep 17, 2026
45 checks passed
@TomasVotruba
TomasVotruba deleted the tv-dead-code-overridden-assign-before-if-else branch September 17, 2026 22:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant