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,29 +84,32 @@ public function refactor(Node $node): ?Node
8284 continue ;
8385 }
8486
85- if (count ($ stmt ->stmts ) !== 1 ) {
87+ $ soleIfReturn = $ this ->matchSoleIfReturn ($ stmt );
88+ if (! $ soleIfReturn instanceof Return_) {
8689 continue ;
8790 }
8891
89- $ soleIfStmt = $ stmt ->stmts [0 ];
90- if (! $ soleIfStmt instanceof Return_) {
92+ if (! $ stmt ->cond instanceof Identical && ! $ stmt ->cond instanceof Equal) {
9193 continue ;
9294 }
9395
94- if (! $ stmt ->cond instanceof Identical && ! $ stmt ->cond instanceof Equal) {
96+ $ identicalOrEqual = $ stmt ->cond ;
97+ // skip obvious complexity
98+ if ($ identicalOrEqual ->right instanceof MethodCall) {
9599 continue ;
96100 }
97101
98- $ identicalOrEqual = $ stmt ->cond ;
99- $ return = $ soleIfStmt ;
102+ if ($ identicalOrEqual ->right instanceof StaticCall) {
103+ continue ;
104+ }
100105
101- if (! $ this ->nodeComparator ->areNodesEqual ($ identicalOrEqual ->right , $ return ->expr )) {
106+ if (! $ this ->nodeComparator ->areNodesEqual ($ identicalOrEqual ->right , $ soleIfReturn ->expr )) {
102107 continue ;
103108 }
104109
105110 $ comparedVariable = $ identicalOrEqual ->left ;
106111
107- // next stmt must be return of the same var
112+ // next if must be return of the same var
108113 $ nextStmt = $ node ->stmts [$ key + 1 ] ?? null ;
109114 if (! $ nextStmt instanceof Return_) {
110115 continue ;
@@ -118,7 +123,7 @@ public function refactor(Node $node): ?Node
118123 continue ;
119124 }
120125
121- // remove next stmt
126+ // remove next if
122127 unset($ node ->stmts [$ key + 1 ]);
123128
124129 // replace if with return
@@ -129,4 +134,18 @@ public function refactor(Node $node): ?Node
129134
130135 return null ;
131136 }
137+
138+ private function matchSoleIfReturn (If_ $ if ): ?Return_
139+ {
140+ if (count ($ if ->stmts ) !== 1 ) {
141+ return null ;
142+ }
143+
144+ $ soleIfStmt = $ if ->stmts [0 ];
145+ if (! $ soleIfStmt instanceof Return_) {
146+ return null ;
147+ }
148+
149+ return $ soleIfStmt ;
150+ }
132151}
0 commit comments