Skip to content

Commit 49eee06

Browse files
authored
Merge pull request #17 from unleashedtech/optimize-namespace-checks
Cache namespaces for faster performance
2 parents 5cfc983 + ef95302 commit 49eee06

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed
+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Unleashed\Helpers;
6+
7+
use PHP_CodeSniffer\Files\File;
8+
9+
/**
10+
* @internal
11+
*
12+
* Adapted from https://github.com/slevomat/coding-standard/blob/c7d4801da5b439cec0d7cd6fa770164b07a4d92b/SlevomatCodingStandard/Helpers/NamespaceHelper.php
13+
*/
14+
final class NamespaceHelper
15+
{
16+
public static function getFirstNamespacePointer(File $phpcsFile): ?int
17+
{
18+
$lazyValue = static function () use ($phpcsFile): ?int {
19+
$token = $phpcsFile->findNext(T_NAMESPACE, 0);
20+
21+
return $token === false ? null : $token;
22+
};
23+
24+
return SniffLocalCache::getAndSetIfNotCached($phpcsFile, 'firstNamespacePointer', $lazyValue);
25+
}
26+
}

src/Unleashed/Sniffs/Namespaces/FullyQualifiedGlobalFunctionsSniff.php

+3-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use PHP_CodeSniffer\Files\File;
88
use PHP_CodeSniffer\Sniffs\Sniff;
99
use SlevomatCodingStandard\Sniffs\Classes\ModernClassNameReferenceSniff;
10+
use Unleashed\Helpers\NamespaceHelper;
1011
use Unleashed\Helpers\UseStatements;
1112

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

0 commit comments

Comments
 (0)