Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace Rector\Tests\Php80\Rector\Ternary\TernaryToNullsafeCoalesceRector\Fixture;

use Rector\Tests\Php80\Rector\Ternary\TernaryToNullsafeCoalesceRector\Source\SomeObject;

final class PropertyCoalesceFallback
{
public function run(?SomeObject $someObject): string
{
return null !== $someObject ? $someObject->name : 'fallback';
}
}

?>
-----
<?php

namespace Rector\Tests\Php80\Rector\Ternary\TernaryToNullsafeCoalesceRector\Fixture;

use Rector\Tests\Php80\Rector\Ternary\TernaryToNullsafeCoalesceRector\Source\SomeObject;

final class PropertyCoalesceFallback
{
public function run(?SomeObject $someObject): string
{
return $someObject->name ?? 'fallback';
}
}

?>
24 changes: 24 additions & 0 deletions rules/Php80/Rector/Ternary/TernaryToNullsafeCoalesceRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,13 @@ public function refactor(Node $node): ?Node
return null;
}

// reading a property on null is already suppressed by "??", so the nullsafe "?->" is
// redundant here and PHPStan reports it; keep the plain "->" chain for property-only
// access, while a method call must stay nullsafe to avoid a call-on-null error
if ($this->isPurePropertyChain($callExpr, $checkedExpr)) {
return new Coalesce($callExpr, $fallbackExpr);
}

return new Coalesce($nullsafeExpr, $fallbackExpr);
}

Expand Down Expand Up @@ -168,6 +175,23 @@ private function createNullsafeChain(Expr $expr, Expr $checkedExpr): ?Expr
return null;
}

/**
* A chain of plain property fetches rooted in the checked expression, e.g. "$a->b->c",
* with no method call in between.
*/
private function isPurePropertyChain(Expr $expr, Expr $checkedExpr): bool
{
if ($this->nodeComparator->areNodesEqual($expr, $checkedExpr)) {
return true;
}

if ($expr instanceof PropertyFetch) {
return $this->isPurePropertyChain($expr->var, $checkedExpr);
}

return false;
}

private function isPureExpr(Expr $expr): bool
{
if ($expr instanceof Variable) {
Expand Down
Loading