Skip to content

Commit

Permalink
UnusedVariableSniff: add scope lookup cache to improve performance
Browse files Browse the repository at this point in the history
  • Loading branch information
nightlinus committed Mar 25, 2020
1 parent 4a32d5b commit 21c41c2
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
29 changes: 29 additions & 0 deletions SlevomatCodingStandard/Helpers/ScopeHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use PHP_CodeSniffer\Files\File;
use function array_reverse;
use function in_array;
use const T_OPEN_TAG;

/**
* @internal
Expand Down Expand Up @@ -34,4 +35,32 @@ public static function isInSameScope(File $phpcsFile, int $firstPointer, int $se
return $getScope($firstPointer) === $getScope($secondPointer);
}

public static function getRootPointer(File $phpcsFile, int $pointer): ?int
{
$roots = array_reverse(self::getAllRootPointers($phpcsFile));
foreach ($roots as $rootPointer) {
if ($rootPointer < $pointer) {
return $rootPointer;
}
}

return null;
}

/**
* @param File $phpcsFile
* @return int[]
*/
public static function getAllRootPointers(File $phpcsFile): array
{
static $cache;
$cache = $cache ?? new SniffLocalCache();

$lazyValue = static function () use ($phpcsFile): array {
return TokenHelper::findNextAll($phpcsFile, T_OPEN_TAG, 0);
};

return $cache->getAndSetIfNotCached($phpcsFile, $lazyValue);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ public function process(File $phpcsFile, $variablePointer): void
return;
}

$scopeOwnerPointer = TokenHelper::findPrevious($phpcsFile, T_OPEN_TAG, $variablePointer - 1);
$scopeOwnerPointer = ScopeHelper::getRootPointer($phpcsFile, $variablePointer - 1);
foreach (array_reverse($tokens[$variablePointer]['conditions'], true) as $conditionPointer => $conditionTokenCode) {
if (in_array($conditionTokenCode, TokenHelper::$functionTokenCodes, true)) {
$scopeOwnerPointer = $conditionPointer;
Expand Down

0 comments on commit 21c41c2

Please sign in to comment.