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

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

final class ReturnInClosure
{
private ?string $name = null;

public function __construct(string $name)
{
$this->name = (function () use ($name): string {
return $name;
})();
}
}

?>
-----
<?php

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

final class ReturnInClosure
{
private ?string $name;

public function __construct(string $name)
{
$this->name = (function () use ($name): string {
return $name;
})();
}
}

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

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

final class SkipEarlyReturnInConstructor
{
public int $x = 0;

public function __construct(bool $shouldReturn = false)
{
if ($shouldReturn) {
return;
}

$this->x = 100;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
use PhpParser\Node\Expr;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Return_;
use Rector\PhpParser\Node\BetterNodeFinder;
use Rector\Rector\AbstractRector;
use Rector\TypeDeclaration\AlreadyAssignDetector\ConstructorAssignDetector;
use Rector\ValueObject\MethodName;
Expand All @@ -20,7 +22,8 @@
final class RemoveDefaultValueFromAssignedPropertyRector extends AbstractRector
{
public function __construct(
private readonly ConstructorAssignDetector $constructorAssignDetector
private readonly ConstructorAssignDetector $constructorAssignDetector,
private readonly BetterNodeFinder $betterNodeFinder
) {
}

Expand Down Expand Up @@ -71,7 +74,13 @@ public function getNodeTypes(): array
*/
public function refactor(Node $node): ?Node
{
if (! $node->getMethod(MethodName::CONSTRUCT) instanceof ClassMethod) {
$constructClassMethod = $node->getMethod(MethodName::CONSTRUCT);
if (! $constructClassMethod instanceof ClassMethod) {
return null;
}

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

Expand Down
Loading