Skip to content

Commit

Permalink
Merge pull request #17 from unleashedtech/optimize-namespace-checks
Browse files Browse the repository at this point in the history
Cache namespaces for faster performance
  • Loading branch information
colinodell authored Oct 20, 2021
2 parents 5cfc983 + ef95302 commit 49eee06
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
26 changes: 26 additions & 0 deletions src/Unleashed/Helpers/NamespaceHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace Unleashed\Helpers;

use PHP_CodeSniffer\Files\File;

/**
* @internal
*
* Adapted from https://github.com/slevomat/coding-standard/blob/c7d4801da5b439cec0d7cd6fa770164b07a4d92b/SlevomatCodingStandard/Helpers/NamespaceHelper.php
*/
final class NamespaceHelper
{
public static function getFirstNamespacePointer(File $phpcsFile): ?int
{
$lazyValue = static function () use ($phpcsFile): ?int {
$token = $phpcsFile->findNext(T_NAMESPACE, 0);

return $token === false ? null : $token;
};

return SniffLocalCache::getAndSetIfNotCached($phpcsFile, 'firstNamespacePointer', $lazyValue);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Sniffs\Classes\ModernClassNameReferenceSniff;
use Unleashed\Helpers\NamespaceHelper;
use Unleashed\Helpers\UseStatements;

final class FullyQualifiedGlobalFunctionsSniff implements Sniff
Expand Down Expand Up @@ -83,7 +84,8 @@ public function register()
public function process(File $phpcsFile, $stackPtr)
{
// Abort if we're not in namespaced code
if ($phpcsFile->findPrevious([T_NAMESPACE], $stackPtr - 1) === false) {
$firstNamespacePointer = NamespaceHelper::getFirstNamespacePointer($phpcsFile);
if ($firstNamespacePointer === null || $stackPtr < $firstNamespacePointer) {
return;
}

Expand Down

0 comments on commit 49eee06

Please sign in to comment.