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

namespace Rector\Tests\DeadCode\Rector\Property\RemoveDefaultValueFromAssignedPropertyRector\Fixture;

final class SkipArrayDimFetchAssign
{
private array $default = [
'name' => 'some name',
'tplset' => null,
];

public function __construct()
{
$this->default['tplset'] = 'dotty';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace Rector\Tests\DeadCode\Rector\Property\RemoveDefaultValueFromAssignedPropertyRector\Fixture;

final class SkipNestedArrayDimFetchAssign
{
private array $config = [
'first' => ['second' => null],
];

public function __construct()
{
$this->config['first']['second'] = 'value';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@

use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Return_;
use Rector\NodeAnalyzer\PropertyFetchAnalyzer;
use Rector\PhpParser\Node\BetterNodeFinder;
use Rector\Rector\AbstractRector;
use Rector\TypeDeclaration\AlreadyAssignDetector\ConstructorAssignDetector;
Expand All @@ -23,7 +26,8 @@ final class RemoveDefaultValueFromAssignedPropertyRector extends AbstractRector
{
public function __construct(
private readonly ConstructorAssignDetector $constructorAssignDetector,
private readonly BetterNodeFinder $betterNodeFinder
private readonly BetterNodeFinder $betterNodeFinder,
private readonly PropertyFetchAnalyzer $propertyFetchAnalyzer
) {
}

Expand Down Expand Up @@ -106,6 +110,11 @@ public function refactor(Node $node): ?Node
continue;
}

// partial assign, e.g. $this->items['key'] = ...; keeps the default value required
if ($this->isAssignedViaArrayDimFetch($node, $propertyName)) {
continue;
}

$propertyProperty->default = null;
$hasChanged = true;
}
Expand All @@ -117,4 +126,25 @@ public function refactor(Node $node): ?Node

return null;
}

private function isAssignedViaArrayDimFetch(Class_ $class, string $propertyName): bool
{
return $this->betterNodeFinder->findFirst($class, function (Node $subNode) use ($propertyName): bool {
if (! $subNode instanceof Assign) {
return false;
}

$assignedExpr = $subNode->var;
if (! $assignedExpr instanceof ArrayDimFetch) {
return false;
}

// unwrap nested dims, e.g. $this->items['first']['second'] = ...
while ($assignedExpr instanceof ArrayDimFetch) {
$assignedExpr = $assignedExpr->var;
}

return $this->propertyFetchAnalyzer->isLocalPropertyFetchName($assignedExpr, $propertyName);
}) instanceof Assign;
}
}
Loading