66
77use PhpParser \Node ;
88use PhpParser \Node \Expr ;
9+ use PhpParser \Node \Expr \ArrayDimFetch ;
10+ use PhpParser \Node \Expr \Assign ;
911use PhpParser \Node \Stmt \Class_ ;
1012use PhpParser \Node \Stmt \ClassMethod ;
1113use PhpParser \Node \Stmt \Return_ ;
14+ use Rector \NodeAnalyzer \PropertyFetchAnalyzer ;
1215use Rector \PhpParser \Node \BetterNodeFinder ;
1316use Rector \Rector \AbstractRector ;
1417use Rector \TypeDeclaration \AlreadyAssignDetector \ConstructorAssignDetector ;
@@ -23,7 +26,8 @@ final class RemoveDefaultValueFromAssignedPropertyRector extends AbstractRector
2326{
2427 public function __construct (
2528 private readonly ConstructorAssignDetector $ constructorAssignDetector ,
26- private readonly BetterNodeFinder $ betterNodeFinder
29+ private readonly BetterNodeFinder $ betterNodeFinder ,
30+ private readonly PropertyFetchAnalyzer $ propertyFetchAnalyzer
2731 ) {
2832 }
2933
@@ -106,6 +110,11 @@ public function refactor(Node $node): ?Node
106110 continue ;
107111 }
108112
113+ // partial assign, e.g. $this->items['key'] = ...; keeps the default value required
114+ if ($ this ->isAssignedViaArrayDimFetch ($ node , $ propertyName )) {
115+ continue ;
116+ }
117+
109118 $ propertyProperty ->default = null ;
110119 $ hasChanged = true ;
111120 }
@@ -117,4 +126,25 @@ public function refactor(Node $node): ?Node
117126
118127 return null ;
119128 }
129+
130+ private function isAssignedViaArrayDimFetch (Class_ $ class , string $ propertyName ): bool
131+ {
132+ return $ this ->betterNodeFinder ->findFirst ($ class , function (Node $ subNode ) use ($ propertyName ): bool {
133+ if (! $ subNode instanceof Assign) {
134+ return false ;
135+ }
136+
137+ $ assignedExpr = $ subNode ->var ;
138+ if (! $ assignedExpr instanceof ArrayDimFetch) {
139+ return false ;
140+ }
141+
142+ // unwrap nested dims, e.g. $this->items['first']['second'] = ...
143+ while ($ assignedExpr instanceof ArrayDimFetch) {
144+ $ assignedExpr = $ assignedExpr ->var ;
145+ }
146+
147+ return $ this ->propertyFetchAnalyzer ->isLocalPropertyFetchName ($ assignedExpr , $ propertyName );
148+ }) instanceof Assign;
149+ }
120150}
0 commit comments