@@ -640,6 +640,9 @@ public static function isTokenInsideArrowFunctionDefinition(File $phpcsFile, $st
640640 */
641641 public static function getContainingArrowFunctionIndex (File $ phpcsFile , $ stackPtr )
642642 {
643+ if (! self ::isTokenInsideArrowFunction ($ phpcsFile , $ stackPtr )) {
644+ return null ;
645+ }
643646 $ arrowFunctionIndex = self ::getPreviousArrowFunctionIndex ($ phpcsFile , $ stackPtr );
644647 if (! is_int ($ arrowFunctionIndex )) {
645648 return null ;
@@ -657,6 +660,38 @@ public static function getContainingArrowFunctionIndex(File $phpcsFile, $stackPt
657660 }
658661
659662 /**
663+ * Move back from the stackPtr to the start of the enclosing scope until we
664+ * find a 'fn' token that starts an arrow function, returning true if we find
665+ * one.
666+ *
667+ * @param File $phpcsFile
668+ * @param int $stackPtr
669+ *
670+ * @return bool
671+ */
672+ private static function isTokenInsideArrowFunction (File $ phpcsFile , $ stackPtr )
673+ {
674+ $ tokens = $ phpcsFile ->getTokens ();
675+ $ enclosingScopeIndex = self ::findVariableScopeExceptArrowFunctions ($ phpcsFile , $ stackPtr );
676+ for ($ index = $ stackPtr - 1 ; $ index > $ enclosingScopeIndex ; $ index --) {
677+ $ token = $ tokens [$ index ];
678+ if ($ token ['content ' ] === 'fn ' && self ::isArrowFunction ($ phpcsFile , $ index )) {
679+ return true ;
680+ }
681+ }
682+ return false ;
683+ }
684+
685+ /**
686+ * Move back from the stackPtr to the start of the enclosing scope until we
687+ * find a 'fn' token that starts an arrow function, returning the index of
688+ * that token. Returns null if we are not inside an arrow function.
689+ *
690+ * NOTE: This is used to find arrow function scope but is not fast because it
691+ * needs to identify nested arrow functions also. Please use
692+ * `isTokenInsideArrowFunction()` instead if you just want to know if we are
693+ * inside an arrow function.
694+ *
660695 * @param File $phpcsFile
661696 * @param int $stackPtr
662697 *
0 commit comments