Skip to content

[Php80] Add TernaryToNullsafeCoalesceRector - #8499

Merged
TomasVotruba merged 2 commits into
rectorphp:mainfrom
guillaume-sainthillier:ternary-to-nullsafe-coalesce
Sep 16, 2026
Merged

TomasVotruba merged 2 commits into
rectorphp:mainfrom
guillaume-sainthillier:ternary-to-nullsafe-coalesce

Conversation

@guillaume-sainthillier

Copy link
Copy Markdown
Contributor

Turns a null-check ternary around a method call or property fetch into the nullsafe operator:

-$value = null !== $dateTime ? $dateTime->format('d/m/Y') : '';
+$value = $dateTime?->format('d/m/Y') ?? '';

TernaryToNullCoalescingRector doesn't catch this one, it only fires when the if-branch is the very same node as the checked expression.

A few notes:

  • a null fallback needs no ?? at all: $a !== null ? $a->getB() : null becomes $a?->getB()
  • any other fallback is only safe when the call itself can't return null, otherwise ?? would swallow it. Guarded with TypeCombinator::containsNull()
  • the checked expression is limited to variables and property fetches, so a call doesn't silently go from two evaluations to one
  • only the deepest link of a chain gets ?->, the rest short-circuits by itself
  • wrapped calls like null !== $d ? strtoupper($d->format('D')) : '' are skipped

NullsafeOperatorRector was removed in #900 for loosening types. That one was if-based and had no check on the return type, this is expression-only and bails out as soon as the call can be null.

@samsonasik samsonasik left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good 👍

@TomasVotruba
TomasVotruba merged commit 23c8825 into rectorphp:main Sep 16, 2026
45 checks passed
@TomasVotruba

Copy link
Copy Markdown
Member

Lets ship it, thank you 👍

@guillaume-sainthillier
guillaume-sainthillier deleted the ternary-to-nullsafe-coalesce branch September 17, 2026 14:45
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.

3 participants