Skip to content

Commit

Permalink
Refactor away from PARENT_NODE in ListToArrayDestructRector (#3982)
Browse files Browse the repository at this point in the history
  • Loading branch information
TomasVotruba committed May 27, 2023
1 parent 0f412e7 commit c70a5b8
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 18 deletions.
Expand Up @@ -7,9 +7,6 @@ class Fixture
public function run()
{
list($id1, $name1) = $data;

foreach ($data as list($id, $name)) {
}
}
}

Expand All @@ -24,9 +21,6 @@ class Fixture
public function run()
{
[$id1, $name1] = $data;

foreach ($data as [$id, $name]) {
}
}
}

Expand Down
@@ -0,0 +1,29 @@
<?php

namespace Rector\Tests\Php71\Rector\List_\ListToArrayDestructRector\Fixture;

final class PartOfForeach
{
public function run()
{
foreach ($data as list($id, $name)) {
}
}
}

?>
-----
<?php

namespace Rector\Tests\Php71\Rector\List_\ListToArrayDestructRector\Fixture;

final class PartOfForeach
{
public function run()
{
foreach ($data as [$id, $name]) {
}
}
}

?>
25 changes: 14 additions & 11 deletions rules/Php71/Rector/List_/ListToArrayDestructRector.php
Expand Up @@ -11,7 +11,6 @@
use PhpParser\Node\Stmt\Foreach_;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\ValueObject\PhpVersionFeature;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
Expand Down Expand Up @@ -61,29 +60,33 @@ public function run()
*/
public function getNodeTypes(): array
{
return [List_::class];
return [Assign::class, Foreach_::class];
}

/**
* @param List_ $node
* @param Assign|Foreach_ $node
*/
public function refactor(Node $node): ?Node
{
$parentNode = $node->getAttribute(AttributeKey::PARENT_NODE);
if ($node instanceof Assign) {
if (! $node->var instanceof List_) {
return null;
}

if ($parentNode instanceof Assign && $parentNode->var === $node) {
return new Array_($node->items);
}
$list = $node->var;

if (! $parentNode instanceof Foreach_) {
return null;
$node->var = new Array_($list->items);
return $node;
}

if ($parentNode->valueVar !== $node) {
if (! $node->valueVar instanceof List_) {
return null;
}

return new Array_($node->items);
$list = $node->valueVar;
$node->valueVar = new Array_($list->items);

return $node;
}

public function provideMinPhpVersion(): int
Expand Down
2 changes: 1 addition & 1 deletion src/Kernel/RectorKernel.php
Expand Up @@ -17,7 +17,7 @@ final class RectorKernel
/**
* @var string
*/
private const CACHE_KEY = 'v34';
private const CACHE_KEY = 'v35';

private ContainerInterface|null $container = null;

Expand Down

0 comments on commit c70a5b8

Please sign in to comment.