Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not search for nested arrow functions outside of arrow functions #341

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions VariableAnalysis/Lib/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,9 @@ public static function isTokenInsideArrowFunctionDefinition(File $phpcsFile, $st
*/
public static function getContainingArrowFunctionIndex(File $phpcsFile, $stackPtr)
{
if (! self::isTokenInsideArrowFunction($phpcsFile, $stackPtr)) {
return null;
}
$arrowFunctionIndex = self::getPreviousArrowFunctionIndex($phpcsFile, $stackPtr);
if (! is_int($arrowFunctionIndex)) {
return null;
Expand All @@ -657,6 +660,38 @@ public static function getContainingArrowFunctionIndex(File $phpcsFile, $stackPt
}

/**
* Move back from the stackPtr to the start of the enclosing scope until we
* find a 'fn' token that starts an arrow function, returning true if we find
* one.
*
* @param File $phpcsFile
* @param int $stackPtr
*
* @return bool
*/
private static function isTokenInsideArrowFunction(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$enclosingScopeIndex = self::findVariableScopeExceptArrowFunctions($phpcsFile, $stackPtr);
for ($index = $stackPtr - 1; $index > $enclosingScopeIndex; $index--) {
$token = $tokens[$index];
if ($token['content'] === 'fn' && self::isArrowFunction($phpcsFile, $index)) {
return true;
}
}
return false;
}

/**
* Move back from the stackPtr to the start of the enclosing scope until we
* find a 'fn' token that starts an arrow function, returning the index of
* that token. Returns null if we are not inside an arrow function.
*
* NOTE: This is used to find arrow function scope but is not fast because it
* needs to identify nested arrow functions also. Please use
* `isTokenInsideArrowFunction()` instead if you just want to know if we are
* inside an arrow function.
*
* @param File $phpcsFile
* @param int $stackPtr
*
Expand Down
Loading