1010use PhpParser \Node \Expr \ArrowFunction ;
1111use PhpParser \Node \Expr \BinaryOp \BooleanAnd ;
1212use PhpParser \Node \Expr \BinaryOp \BooleanOr ;
13+ use PhpParser \Node \Expr \BinaryOp \Equal ;
1314use PhpParser \Node \Expr \BinaryOp \Identical ;
1415use PhpParser \Node \Expr \Closure ;
1516use PhpParser \Node \Expr \FuncCall ;
@@ -122,7 +123,7 @@ public function refactor(Node $node): MethodCall|null
122123 } elseif ($ innerSoleExpr instanceof Identical || $ innerSoleExpr instanceof Instanceof_ || $ innerSoleExpr instanceof Isset_ || ($ innerSoleExpr instanceof FuncCall && $ this ->isName (
123124 $ innerSoleExpr ->name ,
124125 'array_key_exists '
125- )) || $ innerSoleExpr instanceof Expr \ BinaryOp \ Equal) {
126+ )) || $ innerSoleExpr instanceof Equal) {
126127 $ joinedExprs = [$ innerSoleExpr ];
127128 } else {
128129 return null ;
@@ -137,13 +138,28 @@ public function refactor(Node $node): MethodCall|null
137138 return null ;
138139 }
139140
141+ // all stmts but last
142+ $ functionLike = $ argAndFunctionLike ->getFunctionLike ();
143+
144+ if ($ functionLike instanceof Closure) {
145+ $ functionStmts = $ functionLike ->stmts ;
146+
147+ if (count ($ functionStmts ) >= 2 ) {
148+ unset($ functionStmts [array_key_last ($ functionStmts )]);
149+ } else {
150+ $ functionStmts = [];
151+ }
152+ } else {
153+ $ functionStmts = [];
154+ }
155+
140156 // last si return true;
141157 $ assertExpressions [] = new Return_ ($ this ->nodeFactory ->createTrue ());
142158
143159 $ innerFunctionLike = $ argAndFunctionLike ->getFunctionLike ();
144160
145161 if ($ innerFunctionLike instanceof Closure) {
146- $ innerFunctionLike ->stmts = $ assertExpressions ;
162+ $ innerFunctionLike ->stmts = array_merge ( $ functionStmts , $ assertExpressions) ;
147163 } else {
148164 // arrow function -> flip to closure
149165 $ functionLikeInArg = $ argAndFunctionLike ->getArg ();
@@ -218,16 +234,15 @@ private function matchWithCallbackInnerClosure(MethodCall $methodCall): null|Arg
218234 private function matchInnerSoleExpr (Closure |ArrowFunction $ functionLike ): ?Expr
219235 {
220236 if ($ functionLike instanceof Closure) {
221- if (count ($ functionLike ->stmts ) !== 1 ) {
222- return null ;
223- }
237+ foreach ($ functionLike ->getStmts () as $ stmt ) {
238+ if (! $ stmt instanceof Return_) {
239+ continue ;
240+ }
224241
225- $ innerStmt = $ functionLike ->stmts [0 ];
226- if (! $ innerStmt instanceof Return_) {
227- return null ;
242+ return $ stmt ->expr ;
228243 }
229244
230- return $ innerStmt -> expr ;
245+ return null ;
231246 }
232247
233248 return $ functionLike ->expr ;
0 commit comments