Skip to content

Commit

Permalink
[DeadCode] Fix known array type in empty if foreach (#2432)
Browse files Browse the repository at this point in the history
  • Loading branch information
TomasVotruba committed Jun 4, 2022
1 parent 83f7e9f commit 70261b7
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
3 changes: 3 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -722,3 +722,6 @@ parameters:
- '#Method "refactorPhpDoc\(\)" returns bool type, so the name should start with is/has/was#'

- '#Cognitive complexity for "Rector\\Renaming\\Rector\\FileWithoutNamespace\\PseudoNamespaceToNamespaceRector\:\:refactorStmts\(\)" is 11, keep it under 10#'

# resolve later with configurable types
- '#On passing a constant, the method should have an enum type\. See https\://phpstan\.org/writing\-php\-code/phpdoc\-types\#literals\-and\-constants#'
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

namespace Rector\Tests\DeadCode\Rector\If_\RemoveUnusedNonEmptyArrayBeforeForeachRector\Fixture;

final class PropertyForeach
{
private $items = [];

public function __construct(array $items)
{
$this->items = $items;
}

public function run()
{
if ($this->items) {
foreach ($this->items as $item) {
}
}
}
}

?>
-----
<?php

namespace Rector\Tests\DeadCode\Rector\If_\RemoveUnusedNonEmptyArrayBeforeForeachRector\Fixture;

final class PropertyForeach
{
private $items = [];

public function __construct(array $items)
{
$this->items = $items;
}

public function run()
{
foreach ($this->items as $item) {
}
}
}

?>
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt\Foreach_;
use PhpParser\Node\Stmt\If_;
use PHPStan\Type\ArrayType;
use Rector\Core\NodeManipulator\IfManipulator;
use Rector\Core\Php\ReservedKeywordAnalyzer;
use Rector\Core\Rector\AbstractRector;
Expand Down Expand Up @@ -121,6 +122,12 @@ private function isUselessBeforeForeachCheck(If_ $if): bool
return true;
}

// we know it's an array
$condType = $this->getType($if->cond);
if ($condType instanceof ArrayType) {
return true;
}

return $this->countManipulator->isCounterHigherThanOne($if->cond, $foreachExpr);
}
}

0 comments on commit 70261b7

Please sign in to comment.