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,21 @@ public function refactor(Node $node): ?Node
9694 }
9795
9896 $ identicalOrEqual = $ stmt ->cond ;
99- $ return = $ soleIfStmt ;
97+ // skip obvious complexity
98+ if ($ identicalOrEqual ->right instanceof MethodCall) {
99+ continue ;
100+ }
101+ if ($ identicalOrEqual ->right instanceof StaticCall) {
102+ continue ;
103+ }
100104
101- if (! $ this ->nodeComparator ->areNodesEqual ($ identicalOrEqual ->right , $ return ->expr )) {
105+ if (! $ this ->nodeComparator ->areNodesEqual ($ identicalOrEqual ->right , $ soleIfReturn ->expr )) {
102106 continue ;
103107 }
104108
105109 $ comparedVariable = $ identicalOrEqual ->left ;
106110
107- // next stmt must be return of the same var
111+ // next if must be return of the same var
108112 $ nextStmt = $ node ->stmts [$ key + 1 ] ?? null ;
109113 if (! $ nextStmt instanceof Return_) {
110114 continue ;
@@ -118,7 +122,7 @@ public function refactor(Node $node): ?Node
118122 continue ;
119123 }
120124
121- // remove next stmt
125+ // remove next if
122126 unset($ node ->stmts [$ key + 1 ]);
123127
124128 // replace if with return
@@ -129,4 +133,18 @@ public function refactor(Node $node): ?Node
129133
130134 return null ;
131135 }
136+
137+ private function matchSoleIfReturn (If_ $ if ): ?Return_
138+ {
139+ if (count ($ if ->stmts ) !== 1 ) {
140+ return null ;
141+ }
142+
143+ $ soleIfStmt = $ if ->stmts [0 ];
144+ if (! $ soleIfStmt instanceof Return_) {
145+ return null ;
146+ }
147+
148+ return $ soleIfStmt ;
149+ }
132150}
0 commit comments