diff --git a/rules-tests/Php74/Rector/If_/IfToNullCoalescingAssignRector/Fixture/isset_nullable_property.php.inc b/rules-tests/Php74/Rector/If_/IfToNullCoalescingAssignRector/Fixture/isset_nullable_property.php.inc new file mode 100644 index 00000000000..febca5dccb7 --- /dev/null +++ b/rules-tests/Php74/Rector/If_/IfToNullCoalescingAssignRector/Fixture/isset_nullable_property.php.inc @@ -0,0 +1,37 @@ +values)) { + $this->values = ['default']; + } + + return $this->values; + } +} + +?> +----- +values ??= ['default']; + + return $this->values; + } +} + +?> diff --git a/rules/Php74/Rector/If_/IfToNullCoalescingAssignRector.php b/rules/Php74/Rector/If_/IfToNullCoalescingAssignRector.php index 859a9f05117..1b51b6d0679 100644 --- a/rules/Php74/Rector/If_/IfToNullCoalescingAssignRector.php +++ b/rules/Php74/Rector/If_/IfToNullCoalescingAssignRector.php @@ -17,11 +17,13 @@ use PhpParser\Node\Stmt\Else_; use PhpParser\Node\Stmt\Expression; use PhpParser\Node\Stmt\If_; +use PHPStan\Reflection\Php\PhpPropertyReflection; use PHPStan\Type\MixedType; use PHPStan\Type\TypeCombinator; use Rector\PhpParser\Node\BetterNodeFinder; use Rector\PhpParser\Node\Value\ValueResolver; use Rector\Rector\AbstractRector; +use Rector\Reflection\ReflectionResolver; use Rector\ValueObject\PhpVersionFeature; use Rector\VersionBonding\Contract\MinPhpVersionInterface; use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; @@ -34,7 +36,8 @@ final class IfToNullCoalescingAssignRector extends AbstractRector implements Min { public function __construct( private readonly BetterNodeFinder $betterNodeFinder, - private readonly ValueResolver $valueResolver + private readonly ValueResolver $valueResolver, + private readonly ReflectionResolver $reflectionResolver ) { } @@ -127,7 +130,12 @@ private function isNonNullableProperty(Expr $expr): bool return false; } - $propertyType = $this->nodeTypeResolver->getType($expr); + $phpPropertyReflection = $this->reflectionResolver->resolvePropertyReflectionFromPropertyFetch($expr); + if (! $phpPropertyReflection instanceof PhpPropertyReflection) { + return false; + } + + $propertyType = $phpPropertyReflection->getReadableType(); if ($propertyType instanceof MixedType) { return false; }