Skip to content

[Php74] Add IfToNullCoalescingAssignRector to convert if null-guard to ??= - #8356

Merged
TomasVotruba merged 1 commit into
mainfrom
php74-if-to-null-coalescing-assign
Aug 20, 2026
Merged

TomasVotruba merged 1 commit into
mainfrom
php74-if-to-null-coalescing-assign

Conversation

@TomasVotruba

Copy link
Copy Markdown
Member

Closes rectorphp/rector#9843

Adds IfToNullCoalescingAssignRector (Php74 set). It converts an if null-guard around a single self-assignment into the ??= null coalescing assignment operator.

Three guard shapes are recognized:

-if (! isset($array['user_id'])) {
-    $array['user_id'] = 'value';
-}
+$array['user_id'] ??= 'value';
-if (null === $value) {
-    $value = 'default';
-}
+$value ??= 'default';
-if (is_null($this->instance)) {
-    $this->instance = new self();
-}
+$this->instance ??= new self();

Safety guards (rule bails out otherwise)

  • No else / elseif branch.
  • Exactly one statement in the if body, and it is a plain assignment.
  • The assigned target matches the tested expression.
  • The assigned value does not reference the target (skips $x = $x . 'suffix').
  • isset() with more than one variable is skipped.

Both operand orders of the identical check (null === $x and $x === null) are handled.

The rule dogfoods on rector-src itself (8 files simplified in this PR).

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.

[Php74] Add rule to convert if (!isset($x)) { $x = ...; } to ??=

1 participant