-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathDowngradeArraySpreadStringKeyRector.php
More file actions
107 lines (91 loc) · 2.82 KB
/
DowngradeArraySpreadStringKeyRector.php
File metadata and controls
107 lines (91 loc) · 2.82 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
107
<?php
declare(strict_types=1);
namespace Rector\DowngradePhp81\Rector\Array_;
use PhpParser\Node;
use PhpParser\Node\ArrayItem;
use PhpParser\Node\Expr\Array_;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Type\ArrayType;
use PHPStan\Type\Constant\ConstantArrayType;
use PHPStan\Type\IntegerType;
use Rector\DowngradePhp81\NodeAnalyzer\ArraySpreadAnalyzer;
use Rector\DowngradePhp81\NodeFactory\ArrayMergeFromArraySpreadFactory;
use Rector\PHPStan\ScopeFetcher;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @changelog https://wiki.php.net/rfc/array_unpacking_string_keys
*
* @api testing if useful
*
* @see \Rector\Tests\DowngradePhp81\Rector\Array_\DowngradeArraySpreadStringKeyRector\DowngradeArraySpreadStringKeyRectorTest
*/
final class DowngradeArraySpreadStringKeyRector extends AbstractRector
{
public function __construct(
private readonly ArrayMergeFromArraySpreadFactory $arrayMergeFromArraySpreadFactory,
private readonly ArraySpreadAnalyzer $arraySpreadAnalyzer,
) {
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Replace array spread with string key to array_merge function',
[
new CodeSample(
<<<'CODE_SAMPLE'
$parts = ['a' => 'b'];
$parts2 = ['c' => 'd'];
$result = [...$parts, ...$parts2];
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
$parts = ['a' => 'b'];
$parts2 = ['c' => 'd'];
$result = array_merge($parts, $parts2);
CODE_SAMPLE
),
]
);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [Array_::class];
}
/**
* @param Array_ $node
*/
public function refactor(Node $node): ?Node
{
if (! $this->arraySpreadAnalyzer->isArrayWithUnpack($node)) {
return null;
}
if ($this->shouldSkipArray($node)) {
return null;
}
/** @var MutatingScope $scope */
$scope = ScopeFetcher::fetch($node);
return $this->arrayMergeFromArraySpreadFactory->createFromArray($node, $scope);
}
private function shouldSkipArray(Array_ $array): bool
{
foreach ($array->items as $item) {
if (! $item instanceof ArrayItem) {
continue;
}
$type = $this->nodeTypeResolver->getType($item->value);
if (! $type instanceof ArrayType && ! $type instanceof ConstantArrayType) {
continue;
}
$keyType = $type->getKeyType();
if ($keyType instanceof IntegerType) {
return true;
}
}
return false;
}
}