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

Support nested arrow functions #334

Merged
merged 2 commits into from
Nov 18, 2024
Merged
Show file tree
Hide file tree
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
9 changes: 9 additions & 0 deletions Tests/VariableAnalysisSniff/fixtures/ArrowFunctionFixture.php
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,12 @@ function arrowFunctionWithQuotes($allowedReferrers) {
&& $permissionName !== CustomPermission::ALL_CONFIG
);
}

function arrowFunctionWithNestedArrowFunction() {
$fn = fn($outerArrowArg) => [
$outerArrowArg,
fn($insideArg) => $insideArg,
$outerArrowArg,
];
$fn();
}
20 changes: 20 additions & 0 deletions VariableAnalysis/Lib/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,17 @@ private static function getPreviousArrowFunctionIndex(File $phpcsFile, $stackPtr
if ($token['content'] === 'fn' && self::isArrowFunction($phpcsFile, $index)) {
return $index;
}
// If we find a token that would close an arrow function scope before we
// find a token that would open an arrow function scope, then we've found
// a nested arrow function and we should ignore it, move back before THAT
// arrow function's scope, and continue to search.
$arrowFunctionStartIndex = $phpcsFile->findPrevious([T_FN], $index, $enclosingScopeIndex);
if (is_int($arrowFunctionStartIndex)) {
$openClose = self::getArrowFunctionOpenClose($phpcsFile, $arrowFunctionStartIndex);
if ($openClose && $openClose['scope_closer'] === $index) {
$index = $openClose['scope_opener'];
}
}
}
return null;
}
Expand Down Expand Up @@ -646,6 +657,15 @@ public static function isArrowFunction(File $phpcsFile, $stackPtr)
}

/**
* Find the opening and closing scope positions for an arrow function if the
* given position is the start of the arrow function (the `fn` keyword
* token).
*
* Returns null if the passed token is not an arrow function keyword.
*
* If the token is an arrow function keyword, the scope opener is returned as
* the provided position.
*
* @param File $phpcsFile
* @param int $stackPtr
*
Expand Down
Loading