-
-
Notifications
You must be signed in to change notification settings - Fork 439
Expand file tree
/
Copy pathVariableDimFetchAssignResolver.php
More file actions
101 lines (78 loc) · 2.63 KB
/
VariableDimFetchAssignResolver.php
File metadata and controls
101 lines (78 loc) · 2.63 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
<?php
declare(strict_types=1);
namespace Rector\CodeQuality\NodeAnalyzer;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Return_;
use Rector\CodeQuality\ValueObject\KeyAndExpr;
use Rector\Exception\NotImplementedYetException;
use Rector\NodeAnalyzer\ExprAnalyzer;
use Rector\PhpParser\Node\Value\ValueResolver;
final readonly class VariableDimFetchAssignResolver
{
public function __construct(
private ExprAnalyzer $exprAnalyzer,
private ValueResolver $valueResolver
) {
}
/**
* @param Stmt[] $stmts
* @return array<mixed, KeyAndExpr[]>
*/
public function resolveFromStmtsAndVariable(array $stmts, ?Assign $emptyArrayAssign): array
{
$exprs = [];
$key = 0;
foreach ($stmts as $stmt) {
if ($stmt instanceof Expression && $stmt->expr === $emptyArrayAssign) {
continue;
}
if ($stmt instanceof Return_) {
continue;
}
if (! $stmt instanceof Expression) {
return [];
}
$stmtExpr = $stmt->expr;
if (! $stmtExpr instanceof Assign) {
return [];
}
$assign = $stmtExpr;
$dimValues = [];
$arrayDimFetch = $assign->var;
while ($arrayDimFetch instanceof ArrayDimFetch) {
if ($arrayDimFetch->dim instanceof Expr && $this->exprAnalyzer->isDynamicExpr($arrayDimFetch->dim)) {
return [];
}
$dimValues[] = $arrayDimFetch->dim instanceof Expr ? $this->valueResolver->getValue(
$arrayDimFetch->dim
) : $key;
$arrayDimFetch = $arrayDimFetch->var;
}
++$key;
$this->setNestedKeysExpr($exprs, $dimValues, $assign->expr);
}
return $exprs;
}
/**
* @param mixed[] $exprsByKeys
* @param array<string|int> $keys
*/
private function setNestedKeysExpr(array &$exprsByKeys, array $keys, Expr $expr): void
{
$reference = &$exprsByKeys;
$keys = array_reverse($keys);
foreach ($keys as $key) {
if ($reference instanceof Array_) {
// currently it fails here with Cannot use object of type PhpParser\Node\Expr\Array_ as array
throw new NotImplementedYetException();
}
$reference = &$reference[$key];
}
$reference = $expr;
}
}