Skip to content

[CodeQuality] Add InitVariableDefaultBeforeNullCoalesceReturnRector#8091

Closed
TomasVotruba wants to merge 1 commit into
mainfrom
tv-implicit-return
Closed

[CodeQuality] Add InitVariableDefaultBeforeNullCoalesceReturnRector#8091
TomasVotruba wants to merge 1 commit into
mainfrom
tv-implicit-return

Conversation

@TomasVotruba

@TomasVotruba TomasVotruba commented Jun 27, 2026

Copy link
Copy Markdown
Member

Adds InitVariableDefaultBeforeNullCoalesceReturnRector (CodeQuality).

When a variable is only ever filled as an array dimension inside a loop and then returned via ?? <default> to guard the case where the variable was never initialized, this rule moves the default into an explicit init before the first write and drops the null coalesce.

 function run(array $keys): array
 {
+    $result = [];
     foreach ($keys as $key) {
         $result[$key] = $key;
     }

-    return $result ?? [];
+    return $result;
 }

Safe gates

  • return expr is Coalesce, left side is a plain variable, right side is a literal default ([], '', 0, null, ...)
  • the variable is never assigned directly ($x = ...) in the scope (else the ?? guards a real value, skip)
  • the variable is written at least once as an array dimension ($x[...] = ...)
  • the init is inserted directly before the first statement that contains the array-dim write

…o init variable default instead of null coalesce on return
@TomasVotruba TomasVotruba deleted the tv-implicit-return branch June 27, 2026 15:57
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