Skip to content

Commit

Permalink
[CodeQuality] Fix array_keys on object in UnusedForeachValueToArrayKe…
Browse files Browse the repository at this point in the history
…ysRector (#411)
  • Loading branch information
TomasVotruba committed Jul 9, 2021
1 parent cf0284b commit a9ed924
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace Rector\Tests\CodeQuality\Rector\Foreach_\UnusedForeachValueToArrayKeys

class Fixture
{
public function run($values)
public function run(array $values)
{
$items = [];
foreach ($values as $key => $value) {
Expand All @@ -21,7 +21,7 @@ namespace Rector\Tests\CodeQuality\Rector\Foreach_\UnusedForeachValueToArrayKeys

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

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

use PhpCsFixer\Doctrine\Annotation\Token;
use PhpCsFixer\Doctrine\Annotation\Tokens;

final class SkipArrayAccessObject
{
/**
* @param Tokens<Token> $tokens
*/
public function run(Tokens $tokens)
{
$indexes = [];
foreach ($tokens as $index => $token) {
$indexes[] = $index;
}

return $indexes;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Rector\CodeQuality\Rector\Foreach_;

use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\ArrayItem;
use PhpParser\Node\Expr\FuncCall;
Expand Down Expand Up @@ -93,8 +94,7 @@ public function refactor(Node $node): ?Node
return null;
}

$exprType = $this->getStaticType($node->expr);
if ($exprType instanceof ObjectType) {
if (! $this->isArrayType($node->expr)) {
return null;
}

Expand Down Expand Up @@ -152,4 +152,14 @@ private function removeForeachValueAndUseArrayKeys(Foreach_ $foreach): void

$foreach->expr = $this->nodeFactory->createFuncCall('array_keys', [$foreach->expr]);
}

private function isArrayType(Expr $expr): bool
{
$exprType = $this->getStaticType($expr);
if ($exprType instanceof ObjectType) {
return false;
}

return $exprType->isArray()->yes();
}
}

0 comments on commit a9ed924

Please sign in to comment.