Repository navigation
Expand file tree
/
Copy pathChangeArrayPushToArrayAssignRector.php
More file actions
106 lines (89 loc) · 2.55 KB
/
Copy pathChangeArrayPushToArrayAssignRector.php
File metadata and controls
106 lines (89 loc) · 2.55 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
declare(strict_types=1);
namespace Rector\CodeQuality\Rector\FuncCall;
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Expression;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see \Rector\Tests\CodeQuality\Rector\FuncCall\ChangeArrayPushToArrayAssignRector\ChangeArrayPushToArrayAssignRectorTest
*/
final class ChangeArrayPushToArrayAssignRector extends AbstractRector
{
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Change array_push() to direct variable assign',
[
new CodeSample(
<<<'CODE_SAMPLE'
$items = [];
array_push($items, $item);
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
$items = [];
$items[] = $item;
CODE_SAMPLE
),
]
);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [Expression::class];
}
/**
* @param Expression $node
* @return Stmt[]|null
*/
public function refactor(Node $node): ?array
{
if (! $node->expr instanceof FuncCall) {
return null;
}
$funcCall = $node->expr;
if (! $this->isName($funcCall, 'array_push')) {
return null;
}
if ($funcCall->isFirstClassCallable()) {
return null;
}
if ($this->hasArraySpread($funcCall)) {
return null;
}
$args = $funcCall->getArgs();
if ($args === []) {
return null;
}
$firstArg = array_shift($args);
if ($args === []) {
return null;
}
$arrayDimFetch = new ArrayDimFetch($firstArg->value);
$newStmts = [];
foreach ($args as $key => $arg) {
$assign = new Assign($arrayDimFetch, $arg->value);
$assignExpression = new Expression($assign);
$newStmts[] = $assignExpression;
// keep comments of first line
if ($key === 0) {
$this->mirrorComments($assignExpression, $node);
}
}
return $newStmts;
}
private function hasArraySpread(FuncCall $funcCall): bool
{
return array_any($funcCall->getArgs(), fn (Arg $arg): bool => $arg->unpack);
}
}