1616use PhpParser \Node \Stmt \If_ ;
1717use Rector \Contract \PhpParser \Node \StmtsAwareInterface ;
1818use Rector \NodeManipulator \StmtsManipulator ;
19+ use Rector \Php84 \NodeAnalyzer \ForeachKeyUsedInConditionalAnalyzer ;
1920use Rector \PhpParser \Node \Value \ValueResolver ;
2021use Rector \Rector \AbstractRector ;
2122use Rector \ValueObject \PhpVersionFeature ;
@@ -30,7 +31,8 @@ final class ForeachToArrayAllRector extends AbstractRector implements MinPhpVers
3031{
3132 public function __construct (
3233 private readonly ValueResolver $ valueResolver ,
33- private readonly StmtsManipulator $ stmtsManipulator
34+ private readonly StmtsManipulator $ stmtsManipulator ,
35+ private readonly ForeachKeyUsedInConditionalAnalyzer $ foreachKeyUsedInConditionalAnalyzer
3436 ) {
3537 }
3638
@@ -106,7 +108,11 @@ public function refactor(Node $node): ?Node
106108 continue ;
107109 }
108110
109- if ($ this ->stmtsManipulator ->isVariableUsedInNextStmt ($ node , $ key + 1 , (string ) $ this ->getName ($ foreach ->valueVar ))) {
111+ if ($ this ->stmtsManipulator ->isVariableUsedInNextStmt (
112+ $ node ,
113+ $ key + 1 ,
114+ (string ) $ this ->getName ($ foreach ->valueVar )
115+ )) {
110116 continue ;
111117 }
112118
@@ -120,12 +126,19 @@ public function refactor(Node $node): ?Node
120126 continue ;
121127 }
122128
123- $ param = new Param ($ valueParam );
129+ $ params = [new Param ($ valueParam )];
130+
131+ if ($ foreach ->keyVar instanceof Variable && $ this ->foreachKeyUsedInConditionalAnalyzer ->isUsed (
132+ $ foreach ->keyVar ,
133+ $ condition
134+ )) {
135+ $ params [] = new Param (new Variable ((string ) $ this ->getName ($ foreach ->keyVar )));
136+ }
124137
125138 $ negatedCondition = $ condition instanceof BooleanNot ? $ condition ->expr : new BooleanNot ($ condition );
126139
127140 $ arrowFunction = new ArrowFunction ([
128- 'params ' => [ $ param ] ,
141+ 'params ' => $ params ,
129142 'expr ' => $ negatedCondition ,
130143 ]);
131144
0 commit comments