88use PhpParser \Node \Expr ;
99use PhpParser \Node \Expr \BinaryOp \Equal ;
1010use PhpParser \Node \Expr \BinaryOp \Identical ;
11+ use PhpParser \Node \Expr \MethodCall ;
12+ use PhpParser \Node \Expr \StaticCall ;
1113use PhpParser \Node \Stmt \If_ ;
1214use PhpParser \Node \Stmt \Return_ ;
1315use Rector \Contract \PhpParser \Node \StmtsAwareInterface ;
@@ -82,12 +84,8 @@ public function refactor(Node $node): ?Node
8284 continue ;
8385 }
8486
85- if (count ($ stmt ->stmts ) !== 1 ) {
86- continue ;
87- }
88-
89- $ soleIfStmt = $ stmt ->stmts [0 ];
90- if (! $ soleIfStmt instanceof Return_) {
87+ $ soleIfReturn = $ this ->matchSoleIfReturn ($ stmt );
88+ if (! $ soleIfReturn instanceof Return_) {
9189 continue ;
9290 }
9391
@@ -96,15 +94,19 @@ public function refactor(Node $node): ?Node
9694 }
9795
9896 $ identicalOrEqual = $ stmt ->cond ;
99- $ return = $ soleIfStmt ;
10097
101- if (! $ this ->nodeComparator ->areNodesEqual ($ identicalOrEqual ->right , $ return ->expr )) {
98+ // skip obvious complexity
99+ if ($ identicalOrEqual ->right instanceof MethodCall || $ identicalOrEqual ->right instanceof StaticCall) {
100+ continue ;
101+ }
102+
103+ if (! $ this ->nodeComparator ->areNodesEqual ($ identicalOrEqual ->right , $ soleIfReturn ->expr )) {
102104 continue ;
103105 }
104106
105107 $ comparedVariable = $ identicalOrEqual ->left ;
106108
107- // next stmt must be return of the same var
109+ // next if must be return of the same var
108110 $ nextStmt = $ node ->stmts [$ key + 1 ] ?? null ;
109111 if (! $ nextStmt instanceof Return_) {
110112 continue ;
@@ -118,7 +120,7 @@ public function refactor(Node $node): ?Node
118120 continue ;
119121 }
120122
121- // remove next stmt
123+ // remove next if
122124 unset($ node ->stmts [$ key + 1 ]);
123125
124126 // replace if with return
@@ -129,4 +131,18 @@ public function refactor(Node $node): ?Node
129131
130132 return null ;
131133 }
134+
135+ private function matchSoleIfReturn (If_ $ if ): ?Return_
136+ {
137+ if (count ($ if ->stmts ) !== 1 ) {
138+ return null ;
139+ }
140+
141+ $ soleIfStmt = $ if ->stmts [0 ];
142+ if (! $ soleIfStmt instanceof Return_) {
143+ return null ;
144+ }
145+
146+ return $ soleIfStmt ;
147+ }
132148}
0 commit comments