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,23 @@
<?php

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

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

final class SkipMixedReturn
{
public function run(?SomeObject $someObject): mixed
{
return null !== $someObject ? $someObject->findMixed() : '';
}

public function runUntyped(?SomeObject $someObject): mixed
{
return null !== $someObject ? $someObject->findUntyped() : '';
}

public function runUntypedProperty(?SomeObject $someObject): mixed
{
return null !== $someObject ? $someObject->untypedName : '';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ final class SomeObject
{
public string $name = 'name';

public $untypedName = 'name';

public function getName(): string
{
return $this->name;
Expand All @@ -17,4 +19,14 @@ public function findName(): ?string
{
return $this->name;
}

public function findMixed(): mixed
{
return $this->name;
}

public function findUntyped()
{
return $this->name;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
use PhpParser\Node\Expr\StaticPropertyFetch;
use PhpParser\Node\Expr\Ternary;
use PhpParser\Node\Expr\Variable;
use PHPStan\Type\TypeCombinator;
use Rector\PhpParser\Node\Value\ValueResolver;
use Rector\Rector\AbstractRector;
use Rector\ValueObject\PhpVersionFeature;
Expand Down Expand Up @@ -185,13 +184,14 @@ private function isPureExpr(Expr $expr): bool
/**
* Guards the "?? $fallback" rewrite.
*
* The ternary and the coalesce only agree while the call itself cannot return null:
* The ternary and the coalesce only agree while the call itself cannot return null,
* so "mixed" and untyped calls are skipped too:
*
* null !== $a ? $a->find() : '' // $a->find() returning null yields null
* $a?->find() ?? '' // $a->find() returning null yields ''
*/
private function shouldSkipCoalesceFallback(Expr $callExpr): bool
{
return TypeCombinator::containsNull($this->getType($callExpr));
return ! $this->getType($callExpr)->isNull()->no();
}
}
Loading