forked from rectorphp/rector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathListSwapArrayOrderRector.php
76 lines (64 loc) · 2.21 KB
/
ListSwapArrayOrderRector.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
declare(strict_types=1);
namespace Rector\Php70\Rector\Assign;
use PhpParser\Node;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\ArrayItem;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\List_;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\ValueObject\PhpVersionFeature;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @source http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.variable-handling.list
* @see \Rector\Tests\Php70\Rector\Assign\ListSwapArrayOrderRector\ListSwapArrayOrderRectorTest
*/
final class ListSwapArrayOrderRector extends AbstractRector
{
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'list() assigns variables in reverse order - relevant in array assign',
[new CodeSample('list($a[], $a[]) = [1, 2];', 'list($a[], $a[]) = array_reverse([1, 2]);')]
);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [Assign::class];
}
/**
* @param Assign $node
*/
public function refactor(Node $node): ?Node
{
if (! $this->isAtLeastPhpVersion(PhpVersionFeature::LIST_SWAP_ORDER)) {
return null;
}
if (! $node->var instanceof List_) {
return null;
}
$printedVariables = [];
foreach ($node->var->items as $arrayItem) {
if (! $arrayItem instanceof ArrayItem) {
continue;
}
if ($arrayItem->value instanceof ArrayDimFetch && $arrayItem->value->dim === null) {
$printedVariables[] = $this->print($arrayItem->value->var);
} else {
return null;
}
}
// relevant only in 1 variable type
$uniqueVariables = array_unique($printedVariables);
if (count($uniqueVariables) !== 1) {
return null;
}
// wrap with array_reverse, to reflect reverse assign order in left
$node->expr = $this->nodeFactory->createFuncCall('array_reverse', [$node->expr]);
return $node;
}
}