Skip to content

Commit

Permalink
[CodeQuality] Skip non-array type on SimplifyForeachToArrayFilterRect…
Browse files Browse the repository at this point in the history
…or (#3738)

* [CodeQuality] Skip non-array type on SimplifyForeachToArrayFilterRector

* Fixed 🎉

* eol

* pure check ArrayType

* update to use isArray()->yes() usage
  • Loading branch information
samsonasik committed May 6, 2023
1 parent 07e9ccf commit a3ea0cf
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\Foreach_\SimplifyForeachToArrayFilterRector\Fixture;

final class SkipNonArrayType
{
public function __construct(
public int $a,
public ?int $b
) {
}

public function run()
{
$a = new SkipNonArrayType(3, null);

$arr = [];
foreach($a as $k => $v) {
if($v !== null) {
$arr[$k] = $v;
}
}
echo json_encode($arr);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public function __construct(
private readonly ArrayFilterFactory $arrayFilterFactory,
private readonly ExprUsedInNodeAnalyzer $exprUsedInNodeAnalyzer,
private readonly ReadExprAnalyzer $readExprAnalyzer,
private readonly PhpVersionProvider $phpVersionProvider,
private readonly PhpVersionProvider $phpVersionProvider
) {
}

Expand Down Expand Up @@ -128,7 +128,12 @@ private function shouldSkip(Foreach_ $foreach): bool
return true;
}

return $ifNode->elseifs !== [];
if ($ifNode->elseifs !== []) {
return true;
}

$type = $this->getType($foreach->expr);
return ! $type->isArray()->yes();
}

private function shouldSkipForeachKeyUsage(If_ $if, Expr $expr): bool
Expand Down

0 comments on commit a3ea0cf

Please sign in to comment.