@@ -44,15 +44,7 @@ private function processElse(\PHP_CodeSniffer\Files\File $phpcsFile, int $elsePo
4444 {
4545 $ tokens = $ phpcsFile ->getTokens ();
4646
47- $ earlyExitTokenCodes = [T_RETURN , T_CONTINUE , T_BREAK , T_THROW , T_YIELD , T_EXIT ];
48-
49- $ lastSemicolonInElseScopePointer = TokenHelper::findPreviousEffective ($ phpcsFile , $ tokens [$ elsePointer ]['scope_closer ' ] - 1 );
50- if ($ tokens [$ lastSemicolonInElseScopePointer ]['code ' ] !== T_SEMICOLON ) {
51- return ;
52- }
53-
54- $ earlyExitInElseScopePointer = TokenHelper::findPreviousLocal ($ phpcsFile , $ earlyExitTokenCodes , $ lastSemicolonInElseScopePointer - 1 , $ tokens [$ elsePointer ]['scope_opener ' ]);
55- if ($ earlyExitInElseScopePointer === null ) {
47+ if (!$ this ->isEarlyExitInScope ($ phpcsFile , $ tokens [$ elsePointer ]['scope_opener ' ], $ tokens [$ elsePointer ]['scope_closer ' ])) {
5648 return ;
5749 }
5850
@@ -65,12 +57,7 @@ private function processElse(\PHP_CodeSniffer\Files\File $phpcsFile, int $elsePo
6557
6658 $ ifPointer = $ previousConditionPointer ;
6759
68- $ lastSemicolonInIfScopePointer = TokenHelper::findPreviousEffective ($ phpcsFile , $ tokens [$ ifPointer ]['scope_closer ' ] - 1 );
69- $ isEarlyExitInIfScope = $ tokens [$ lastSemicolonInIfScopePointer ]['code ' ] === T_SEMICOLON
70- ? TokenHelper::findPreviousLocal ($ phpcsFile , $ earlyExitTokenCodes , $ lastSemicolonInIfScopePointer - 1 , $ tokens [$ ifPointer ]['scope_opener ' ]) !== null
71- : false ;
72-
73- if ($ isEarlyExitInIfScope ) {
60+ if ($ this ->isEarlyExitInScope ($ phpcsFile , $ tokens [$ ifPointer ]['scope_opener ' ], $ tokens [$ ifPointer ]['scope_closer ' ])) {
7461 $ fix = $ phpcsFile ->addFixableError (
7562 'Remove useless else to reduce code nesting. ' ,
7663 $ elsePointer ,
@@ -153,6 +140,10 @@ private function processIf(\PHP_CodeSniffer\Files\File $phpcsFile, int $ifPointe
153140 return ;
154141 }
155142
143+ if ($ this ->isEarlyExitInScope ($ phpcsFile , $ tokens [$ ifPointer ]['scope_opener ' ], $ tokens [$ ifPointer ]['scope_closer ' ])) {
144+ return ;
145+ }
146+
156147 $ fix = $ phpcsFile ->addFixableError (
157148 'Use early exit to reduce code nesting. ' ,
158149 $ ifPointer ,
@@ -341,4 +332,12 @@ private function fixIndentation(string $code, string $eolChar, string $defaultIn
341332 }, explode ($ eolChar , rtrim ($ code ))));
342333 }
343334
335+ private function isEarlyExitInScope (\PHP_CodeSniffer \Files \File $ phpcsFile , int $ startPointer , int $ endPointer ): bool
336+ {
337+ $ lastSemicolonInScopePointer = TokenHelper::findPreviousEffective ($ phpcsFile , $ endPointer - 1 );
338+ return $ phpcsFile ->getTokens ()[$ lastSemicolonInScopePointer ]['code ' ] === T_SEMICOLON
339+ ? TokenHelper::findPreviousLocal ($ phpcsFile , TokenHelper::$ earlyExitTokenCodes , $ lastSemicolonInScopePointer - 1 , $ startPointer ) !== null
340+ : false ;
341+ }
342+
344343}
0 commit comments