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\DeadCode\Rector\Property\RemoveDefaultValueFromAssignedPropertyRector\Fixture;

final class SkipEarlyReturnInCalledMethod
{
private array $unknownLeadIds = [];

public function __construct(
private readonly array $campaignMembers,
) {
$this->fetchLeads();
}

private function fetchLeads(): void
{
if ($this->campaignMembers === []) {
return;
}

$this->unknownLeadIds = $this->campaignMembers;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Return_;
use Rector\Configuration\Parameter\FeatureFlags;
use Rector\NodeAnalyzer\PropertyFetchAnalyzer;
Expand Down Expand Up @@ -85,7 +87,7 @@ public function refactor(Node $node): ?Node
}

// early return can skip the assign, so the default value is still needed
if ($this->betterNodeFinder->hasInstancesOfInFunctionLikeScoped($constructClassMethod, Return_::class)) {
if ($this->hasEarlyReturn($node, $constructClassMethod)) {
return null;
}

Expand Down Expand Up @@ -138,6 +140,47 @@ public function refactor(Node $node): ?Node
return null;
}

/**
* The constructor itself, or any local method it calls, can skip the assign with an early return
*/
private function hasEarlyReturn(Class_ $class, ClassMethod $constructClassMethod): bool
{
if ($this->betterNodeFinder->hasInstancesOfInFunctionLikeScoped($constructClassMethod, Return_::class)) {
return true;
}

foreach ((array) $constructClassMethod->stmts as $stmt) {
if (! $stmt instanceof Expression) {
continue;
}

if (! $stmt->expr instanceof MethodCall) {
continue;
}

$methodCall = $stmt->expr;
if (! $this->isName($methodCall->var, 'this')) {
continue;
}

$methodName = $this->getName($methodCall->name);
if ($methodName === null) {
continue;
}

$calledClassMethod = $class->getMethod($methodName);
if (! $calledClassMethod instanceof ClassMethod) {
continue;
}

if ($this->betterNodeFinder->hasInstancesOfInFunctionLikeScoped($calledClassMethod, Return_::class)) {
return true;
}
}

return false;
}

private function isAssignedViaArrayDimFetch(Class_ $class, string $propertyName): bool
{
return $this->betterNodeFinder->findFirst($class, function (Node $subNode) use ($propertyName): bool {
Expand Down
Loading