Skip to content

Commit

Permalink
[DeadCode] Fix infinite loop on RemoveDeadStmtRector + RemoveUnusedVa…
Browse files Browse the repository at this point in the history
…riableAssignRector (#5666)
  • Loading branch information
samsonasik committed Feb 27, 2024
1 parent 58abec4 commit a56ee1e
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 2 deletions.
5 changes: 3 additions & 2 deletions rules/DeadCode/Rector/Expression/RemoveDeadStmtRector.php
Expand Up @@ -76,14 +76,15 @@ public function refactor(Node $node): array|Node|null|int
return null;
}

$node->expr = array_shift($livingCode);
$newNode = clone $node;
$newNode->expr = array_shift($livingCode);

$newNodes = [];
foreach ($livingCode as $singleLivingCode) {
$newNodes[] = new Expression($singleLivingCode);
}

$newNodes[] = $node;
$newNodes[] = $newNode;

return $newNodes;
}
Expand Down
28 changes: 28 additions & 0 deletions tests/Issues/InfiniteLoop/DeadStmtUnusedVariableTest.php
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\Issues\InfiniteLoop;

use Iterator;
use PHPUnit\Framework\Attributes\DataProvider;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;

final class DeadStmtUnusedVariableTest extends AbstractRectorTestCase
{
#[DataProvider('provideData')]
public function test(string $filePath): void
{
$this->doTestFile($filePath);
}

public static function provideData(): Iterator
{
return self::yieldFilesFromDirectory(__DIR__ . '/FixtureDeadStmtUnusedVariable');
}

public function provideConfigFilePath(): string
{
return __DIR__ . '/config/dead_stmt_unused_variable.php';
}
}
@@ -0,0 +1,28 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\BooleanNot\SimplifyDeMorganBinaryRector\FixtureDeadStmtUnusedVariable;

class X
{
public function f()
{
$var = $object->a() . $object->b();
}
}

?>
-----
<?php

namespace Rector\Tests\CodeQuality\Rector\BooleanNot\SimplifyDeMorganBinaryRector\FixtureDeadStmtUnusedVariable;

class X
{
public function f()
{
$object->b();
$object->a();
}
}

?>
13 changes: 13 additions & 0 deletions tests/Issues/InfiniteLoop/config/dead_stmt_unused_variable.php
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\DeadCode\Rector\Assign\RemoveUnusedVariableAssignRector;
use Rector\DeadCode\Rector\Expression\RemoveDeadStmtRector;

return RectorConfig::configure()
->withRules([
RemoveDeadStmtRector::class,
RemoveUnusedVariableAssignRector::class
]);

0 comments on commit a56ee1e

Please sign in to comment.