diff --git a/rules-tests/DeadCode/Rector/Property/RemoveDefaultValueFromAssignedPropertyRector/Fixture/return_in_closure.php.inc b/rules-tests/DeadCode/Rector/Property/RemoveDefaultValueFromAssignedPropertyRector/Fixture/return_in_closure.php.inc new file mode 100644 index 00000000000..f625cedce20 --- /dev/null +++ b/rules-tests/DeadCode/Rector/Property/RemoveDefaultValueFromAssignedPropertyRector/Fixture/return_in_closure.php.inc @@ -0,0 +1,35 @@ +name = (function () use ($name): string { + return $name; + })(); + } +} + +?> +----- +name = (function () use ($name): string { + return $name; + })(); + } +} + +?> diff --git a/rules-tests/DeadCode/Rector/Property/RemoveDefaultValueFromAssignedPropertyRector/Fixture/skip_early_return_in_constructor.php.inc b/rules-tests/DeadCode/Rector/Property/RemoveDefaultValueFromAssignedPropertyRector/Fixture/skip_early_return_in_constructor.php.inc new file mode 100644 index 00000000000..d992a059aea --- /dev/null +++ b/rules-tests/DeadCode/Rector/Property/RemoveDefaultValueFromAssignedPropertyRector/Fixture/skip_early_return_in_constructor.php.inc @@ -0,0 +1,17 @@ +x = 100; + } +} diff --git a/rules/DeadCode/Rector/Property/RemoveDefaultValueFromAssignedPropertyRector.php b/rules/DeadCode/Rector/Property/RemoveDefaultValueFromAssignedPropertyRector.php index f4e8d355550..6dd4b633d5a 100644 --- a/rules/DeadCode/Rector/Property/RemoveDefaultValueFromAssignedPropertyRector.php +++ b/rules/DeadCode/Rector/Property/RemoveDefaultValueFromAssignedPropertyRector.php @@ -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; @@ -20,7 +22,8 @@ final class RemoveDefaultValueFromAssignedPropertyRector extends AbstractRector { public function __construct( - private readonly ConstructorAssignDetector $constructorAssignDetector + private readonly ConstructorAssignDetector $constructorAssignDetector, + private readonly BetterNodeFinder $betterNodeFinder ) { } @@ -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; }