rector/rules/Php71/Rector/List_/ListToArrayDestructRector.php

83 lines
2.1 KiB
PHP
Raw Permalink Normal View History

2019-10-13 05:59:52 +00:00
<?php
declare (strict_types=1);
namespace Rector\Php71\Rector\List_;
2019-09-25 23:52:55 +00:00
use PhpParser\Node;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\List_;
use PhpParser\Node\Stmt\Foreach_;
use Rector\Rector\AbstractRector;
use Rector\ValueObject\PhpVersionFeature;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
2019-09-25 23:52:55 +00:00
/**
2021-04-10 18:47:17 +00:00
* @changelog https://wiki.php.net/rfc/short_list_syntax https://www.php.net/manual/en/migration71.new-features.php#migration71.new-features.symmetric-array-destructuring
*
* @see \Rector\Tests\Php71\Rector\List_\ListToArrayDestructRector\ListToArrayDestructRectorTest
2019-09-25 23:52:55 +00:00
*/
final class ListToArrayDestructRector extends AbstractRector implements MinPhpVersionInterface
2019-09-25 23:52:55 +00:00
{
public function getRuleDefinition() : RuleDefinition
2019-09-25 23:52:55 +00:00
{
return new RuleDefinition('Change list() to array destruct', [new CodeSample(<<<'CODE_SAMPLE'
2019-09-25 23:52:55 +00:00
class SomeClass
{
public function run()
{
list($id1, $name1) = $data;
foreach ($data as list($id, $name)) {
}
}
}
CODE_SAMPLE
, <<<'CODE_SAMPLE'
2019-09-25 23:52:55 +00:00
class SomeClass
{
public function run()
{
[$id1, $name1] = $data;
foreach ($data as [$id, $name]) {
}
}
}
CODE_SAMPLE
)]);
2019-09-25 23:52:55 +00:00
}
/**
* @return array<class-string<Node>>
2019-09-25 23:52:55 +00:00
*/
public function getNodeTypes() : array
2019-09-25 23:52:55 +00:00
{
return [Assign::class, Foreach_::class];
2019-09-25 23:52:55 +00:00
}
/**
* @param Assign|Foreach_ $node
2019-09-25 23:52:55 +00:00
*/
public function refactor(Node $node) : ?Node
2019-09-25 23:52:55 +00:00
{
if ($node instanceof Assign) {
if (!$node->var instanceof List_) {
return null;
}
$list = $node->var;
$node->var = new Array_($list->items);
return $node;
2019-09-25 23:52:55 +00:00
}
if (!$node->valueVar instanceof List_) {
return null;
2019-09-25 23:52:55 +00:00
}
$list = $node->valueVar;
$node->valueVar = new Array_($list->items);
return $node;
2019-09-25 23:52:55 +00:00
}
public function provideMinPhpVersion() : int
{
return PhpVersionFeature::ARRAY_DESTRUCT;
}
2019-09-25 23:52:55 +00:00
}