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
2 changes: 2 additions & 0 deletions config/set/php74.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Rector\Php74\Rector\FuncCall\MbStrrposEncodingArgumentPositionRector;
use Rector\Php74\Rector\FuncCall\MoneyFormatToNumberFormatRector;
use Rector\Php74\Rector\FuncCall\RestoreIncludePathToIniRestoreRector;
use Rector\Php74\Rector\If_\IfToNullCoalescingAssignRector;
use Rector\Php74\Rector\Property\RestoreDefaultNullToNullableTypePropertyRector;
use Rector\Php74\Rector\StaticCall\ExportToReflectionFunctionRector;
use Rector\Php74\Rector\Ternary\ParenthesizeNestedTernaryRector;
Expand All @@ -34,6 +35,7 @@
ExportToReflectionFunctionRector::class,
MbStrrposEncodingArgumentPositionRector::class,
NullCoalescingOperatorRector::class,
IfToNullCoalescingAssignRector::class,
ClosureToArrowFunctionRector::class,
RestoreDefaultNullToNullableTypePropertyRector::class,
CurlyToSquareBracketArrayStringRector::class,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

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

class IsNullProperty
{
private $instance;

public function get()
{
if (is_null($this->instance)) {
$this->instance = new self();
}

return $this->instance;
}
}

?>
-----
<?php

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

class IsNullProperty
{
private $instance;

public function get()
{
$this->instance ??= new self();

return $this->instance;
}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

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

$array = [];
if (! isset($array['user_id'])) {
$array['user_id'] = 'value';
}

?>
-----
<?php

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

$array = [];
$array['user_id'] ??= 'value';

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

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

function nullIdenticalVariable($value)
{
if (null === $value) {
$value = 'default';
}
}

function variableIdenticalNull($value)
{
if ($value === null) {
$value = 'default';
}
}

?>
-----
<?php

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

function nullIdenticalVariable($value)
{
$value ??= 'default';
}

function variableIdenticalNull($value)
{
$value ??= 'default';
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

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

function skipDifferentTarget($value, $other)
{
if (null === $value) {
$other = 'default';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

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

function skipElse($value)
{
if (null === $value) {
$value = 'default';
} else {
$value = 'other';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

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

function skipMultipleIssetVars($first, $second)
{
if (! isset($first, $second)) {
$first = 'default';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

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

function skipMultipleStmts($value)
{
if (null === $value) {
$value = 'default';
echo $value;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

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

function skipSelfReference($value)
{
if (null === $value) {
$value = $value . 'suffix';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

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

use Iterator;
use PHPUnit\Framework\Attributes\DataProvider;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;

final class IfToNullCoalescingAssignRectorTest extends AbstractRectorTestCase
{
#[DataProvider('provideData')]
public function test(string $filePath): void
{
$this->doTestFile($filePath);
}

public static function provideData(): Iterator
{
return self::yieldFilesFromDirectory(__DIR__ . '/Fixture');
}

public function provideConfigFilePath(): string
{
return __DIR__ . '/config/configured_rule.php';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Php74\Rector\If_\IfToNullCoalescingAssignRector;

return RectorConfig::configure()
->withRules([IfToNullCoalescingAssignRector::class]);
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,7 @@ public function getNodeTypes(): array
*/
public function refactor(Node $node): null|array|int
{
/**
* $this->phpVersionProvider->provide() fallback is here as $currentFileProvider must be accessed after initialization
*/
if ($this->phpVersion === null) {
$this->phpVersion = $this->phpVersionProvider->provide();
}
$this->phpVersion ??= $this->phpVersionProvider->provide();

if (! $node->cond instanceof BinaryOp) {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,7 @@ private function resolve(ClassLike $classLike): array
$expectedNames = [];
foreach ($classLike->getProperties() as $property) {
$expectedName = $this->matchPropertyTypeExpectedNameResolver->resolve($property, $classLike);
if ($expectedName === null) {
// fallback to existing name
$expectedName = $this->nodeNameResolver->getName($property);
}
$expectedName ??= $this->nodeNameResolver->getName($property);

$expectedNames[] = $expectedName;
}
Expand Down
153 changes: 153 additions & 0 deletions rules/Php74/Rector/If_/IfToNullCoalescingAssignRector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
<?php

declare(strict_types=1);

namespace Rector\Php74\Rector\If_;

use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\AssignOp\Coalesce as AssignCoalesce;
use PhpParser\Node\Expr\BinaryOp\Identical;
use PhpParser\Node\Expr\BooleanNot;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\Isset_;
use PhpParser\Node\Stmt\Else_;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\If_;
use Rector\PhpParser\Node\BetterNodeFinder;
use Rector\PhpParser\Node\Value\ValueResolver;
use Rector\Rector\AbstractRector;
use Rector\ValueObject\PhpVersionFeature;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @see \Rector\Tests\Php74\Rector\If_\IfToNullCoalescingAssignRector\IfToNullCoalescingAssignRectorTest
*/
final class IfToNullCoalescingAssignRector extends AbstractRector implements MinPhpVersionInterface
{
public function __construct(
private readonly BetterNodeFinder $betterNodeFinder,
private readonly ValueResolver $valueResolver
) {
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Change `if` null guard with single assign to null coalescing assign `??=`', [
new CodeSample(
<<<'CODE_SAMPLE'
if (! isset($array['user_id'])) {
$array['user_id'] = 'value';
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
$array['user_id'] ??= 'value';
CODE_SAMPLE
),
]);
}

/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [If_::class];
}

/**
* @param If_ $node
*/
public function refactor(Node $node): ?Expression
{
if ($node->else instanceof Else_) {
return null;
}

if ($node->elseifs !== []) {
return null;
}

if (count($node->stmts) !== 1) {
return null;
}

$onlyStmt = $node->stmts[0];
if (! $onlyStmt instanceof Expression) {
return null;
}

$assign = $onlyStmt->expr;
if (! $assign instanceof Assign) {
return null;
}

$testedExpr = $this->matchNullGuardedExpr($node->cond);
if (! $testedExpr instanceof Expr) {
return null;
}

if (! $this->nodeComparator->areNodesEqual($assign->var, $testedExpr)) {
return null;
}

// the assigned value must not reference the target, e.g. $x = $x + 1
$selfReference = $this->betterNodeFinder->findFirst(
$assign->expr,
fn (Node $subNode): bool => $this->nodeComparator->areNodesEqual($subNode, $assign->var)
);
if ($selfReference instanceof Node) {
return null;
}

return new Expression(new AssignCoalesce($assign->var, $assign->expr));
}

public function provideMinPhpVersion(): int
{
return PhpVersionFeature::NULL_COALESCE_ASSIGN;
}

private function matchNullGuardedExpr(Expr $expr): ?Expr
{
// ! isset($value)
if ($expr instanceof BooleanNot && $expr->expr instanceof Isset_) {
if (count($expr->expr->vars) !== 1) {
return null;
}

return $expr->expr->vars[0];
}

// is_null($value)
if ($expr instanceof FuncCall && $this->isName($expr, 'is_null')) {
if ($expr->isFirstClassCallable()) {
return null;
}

if (count($expr->getArgs()) !== 1) {
return null;
}

return $expr->getArgs()[0]
->value;
}

// null === $value or $value === null
if ($expr instanceof Identical) {
if ($this->valueResolver->isNull($expr->left)) {
return $expr->right;
}

if ($this->valueResolver->isNull($expr->right)) {
return $expr->left;
}
}

return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,7 @@ public function resolveTagFullyQualifiedName(string $tag, Node $node): string
$uses = $this->useImportsResolver->resolve();
$fullyQualifiedClass = $this->resolveFullyQualifiedClass($uses, $node, $tag);

if ($fullyQualifiedClass === null) {
$fullyQualifiedClass = $tag;
}
$fullyQualifiedClass ??= $tag;

$this->fullyQualifiedNameByHash[$uniqueId] = $fullyQualifiedClass;

Expand Down
Loading
Loading