Skip to content

Commit

Permalink
[CodeQuality] Skip not ArrayType on ForeachItemsAssignToEmptyArrayToA…
Browse files Browse the repository at this point in the history
…ssignRector (#2752)

Co-authored-by: Gocha Ossinkine <ossinkine@ya.ru>
  • Loading branch information
samsonasik and ossinkine committed Aug 10, 2022
1 parent 77a0b34 commit c0070b1
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace Rector\Tests\CodeQuality\Rector\Foreach_\ForeachItemsAssignToEmptyArra

class Fixture
{
public function run($items)
public function run(array $items)
{
$items2 = [];
foreach ($items as $item) {
Expand All @@ -21,7 +21,7 @@ namespace Rector\Tests\CodeQuality\Rector\Foreach_\ForeachItemsAssignToEmptyArra

class Fixture
{
public function run($items)
public function run(array $items)
{
$items2 = [];
$items2 = $items;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

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

class SkipMixedType
{
public function run($items)
{
$items2 = [];
foreach ($items as $item) {
$items2[] = $item;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

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

class SkipTraversable
{
public function run()
{
$items = [];
foreach ($this->getTraversable() as $item) {
$items[] = $item;
}
}

private function getTraversable(): iterable
{
yield 123;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Stmt\Foreach_;
use PHPStan\Analyser\Scope;
use PHPStan\Type\ObjectType;
use PHPStan\Type\ThisType;
use PHPStan\Type\ArrayType;
use Rector\CodeQuality\NodeAnalyzer\ForeachAnalyzer;
use Rector\Core\Rector\AbstractScopeAwareRector;
use Rector\NodeNestingScope\ValueObject\ControlStructure;
Expand Down Expand Up @@ -117,18 +116,7 @@ private function shouldSkip(Foreach_ $foreach, Scope $scope): bool
}

$type = $scope->getType($foreach->expr);

if ($type instanceof ObjectType) {
return $type->isIterable()
->yes();
}

if ($type instanceof ThisType) {
return $type->isIterable()
->yes();
}

return false;
return ! $type instanceof ArrayType;
}

private function shouldSkipAsPartOfOtherLoop(Foreach_ $foreach): bool
Expand Down

0 comments on commit c0070b1

Please sign in to comment.