Skip to content

Commit

Permalink
[DeadCode] Skip do { } while() on RemoveUnreachableStatementRector (#601
Browse files Browse the repository at this point in the history
)

* [DeadCode] Skip do { } while() on RemoveUnreachableStatementRector

* eol

* move to const
  • Loading branch information
samsonasik committed Aug 5, 2021
1 parent f668ee2 commit 7c937fa
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace Rector\Tests\DeadCode\Rector\Stmt\RemoveUnreachableStatementRector\Fixture;

function skipDoWhile(array $array): array
{
if ($array === []) {
return [];
}

$new = [];

do {
array_splice($array, 0, 1);
$new[] = strtoupper(current($array));
} while (count($array) > 0);

return $new;
}

?>
19 changes: 11 additions & 8 deletions rules/DeadCode/Rector/Stmt/RemoveUnreachableStatementRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Do_;
use PhpParser\Node\Stmt\Else_;
use PhpParser\Node\Stmt\Function_;
use PhpParser\Node\Stmt\If_;
Expand All @@ -29,6 +30,11 @@
*/
final class RemoveUnreachableStatementRector extends AbstractRector
{
/**
* @var array<class-string<Node>>
*/
private const STMTS_WITH_IS_UNREACHABLE = [If_::class, While_::class, Do_::class];

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Remove unreachable statements', [
Expand Down Expand Up @@ -77,14 +83,11 @@ public function refactor(Node $node): ?Node

// might be PHPStan false positive, better skip
$previousStatement = $node->getAttribute(AttributeKey::PREVIOUS_STATEMENT);
if ($previousStatement instanceof If_) {
$node->setAttribute(
AttributeKey::IS_UNREACHABLE,
$previousStatement->getAttribute(AttributeKey::IS_UNREACHABLE)
);
}

if ($previousStatement instanceof While_) {
if ($previousStatement instanceof Stmt && in_array(
$previousStatement::class,
self::STMTS_WITH_IS_UNREACHABLE,
true
)) {
$node->setAttribute(
AttributeKey::IS_UNREACHABLE,
$previousStatement->getAttribute(AttributeKey::IS_UNREACHABLE)
Expand Down

0 comments on commit 7c937fa

Please sign in to comment.