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

namespace Rector\Tests\DeadCode\Rector\For_\RemoveDeadLoopRector\Fixture;

use DateTimeImmutable;

final class SkipWithSideEffect
{
public function run()
{
$arr = [
new DateTimeImmutable("2025-03-10 00:00:00"),
new DateTimeImmutable("2025-03-14 00:00:00"),
new DateTimeImmutable("2025-03-18 00:00:00"),
new DateTimeImmutable("2025-03-22 00:00:00"),
new DateTimeImmutable("2025-03-26 00:00:00"),
new DateTimeImmutable("2025-03-30 00:00:00"),
];
$checkDate = new DateTimeImmutable("2025-03-20 00:00:00");
for($foundDate = array_shift($arr); $foundDate !== null && $foundDate < $checkDate; $foundDate = array_shift($arr));

var_dump($foundDate);
}
}
28 changes: 28 additions & 0 deletions rules/DeadCode/Rector/For_/RemoveDeadLoopRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@
namespace Rector\DeadCode\Rector\For_;

use PhpParser\Node;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Stmt\Do_;
use PhpParser\Node\Stmt\For_;
use PhpParser\Node\Stmt\Foreach_;
use PhpParser\Node\Stmt\While_;
use PhpParser\NodeVisitor;
use Rector\DeadCode\SideEffect\SideEffectNodeDetector;
use Rector\PHPStan\ScopeFetcher;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
Expand All @@ -19,6 +22,11 @@
*/
final class RemoveDeadLoopRector extends AbstractRector
{
public function __construct(
private readonly SideEffectNodeDetector $sideEffectNodeDetector
) {
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
Expand Down Expand Up @@ -66,6 +74,26 @@ public function refactor(Node $node): ?int
return null;
}

if ($node instanceof Do_ || $node instanceof While_) {
$exprs = [$node->cond];
} elseif ($node instanceof For_) {
$exprs = [...$node->init, ...$node->cond, ...$node->loop];
} else {
$exprs = [$node->expr, $node->valueVar];
}

$scope = ScopeFetcher::fetch($node);

foreach ($exprs as $expr) {
if ($expr instanceof Assign) {
$expr = $expr->expr;
}

if ($this->sideEffectNodeDetector->detect($expr, $scope)) {
return null;
}
}

return NodeVisitor::REMOVE_NODE;
}
}