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

namespace Rector\Tests\Php74\Rector\If_\IfToNullCoalescingAssignRector\Fixture;

class SkipTypedNonNullableProperty
{
private static array $parameters;

public function get(): array
{
if (! isset(self::$parameters)) {
self::$parameters = ['default'];
}

return self::$parameters;
}
}
23 changes: 23 additions & 0 deletions rules/Php74/Rector/If_/IfToNullCoalescingAssignRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,13 @@
use PhpParser\Node\Expr\BooleanNot;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\Isset_;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\StaticPropertyFetch;
use PhpParser\Node\Stmt\Else_;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\If_;
use PHPStan\Type\MixedType;
use PHPStan\Type\TypeCombinator;
use Rector\PhpParser\Node\BetterNodeFinder;
use Rector\PhpParser\Node\Value\ValueResolver;
use Rector\Rector\AbstractRector;
Expand Down Expand Up @@ -95,6 +99,11 @@ public function refactor(Node $node): ?Expression
return null;
}

// a typed non-nullable property can never be null on the left of ??=
if ($this->isNonNullableProperty($testedExpr)) {
return null;
}

// the assigned value must not reference the target, e.g. $x = $x + 1
$selfReference = $this->betterNodeFinder->findFirst(
$assign->expr,
Expand All @@ -112,6 +121,20 @@ public function provideMinPhpVersion(): int
return PhpVersionFeature::NULL_COALESCE_ASSIGN;
}

private function isNonNullableProperty(Expr $expr): bool
{
if (! $expr instanceof PropertyFetch && ! $expr instanceof StaticPropertyFetch) {
return false;
}

$propertyType = $this->nodeTypeResolver->getType($expr);
if ($propertyType instanceof MixedType) {
return false;
}

return ! TypeCombinator::containsNull($propertyType);
}

private function matchNullGuardedExpr(Expr $expr): ?Expr
{
// ! isset($value)
Expand Down
Loading