From 5c805749fdd0b6edbc1e6aa4c55d7b6bff8ef665 Mon Sep 17 00:00:00 2001 From: Ewart Xia Date: Fri, 15 May 2026 11:40:22 -0700 Subject: [PATCH] Fix NamespaceDirectoryNameSniff misreading strict_types as namespace name The sniff calls findNext(T_STRING, 0) on line 33 to locate the namespace name, which starts searching from position 0 of the file. When the file opens with a declare(strict_types=1) statement before its namespace declaration, the first T_STRING token in the file is strict_types (PHP tokenizes the declare directive name as T_STRING), so the sniff reads strict_types as the namespace and reports a false NameMismatch or ExtraDirs error against the actual directory. Change the search start position to $stackPtr so the namespace name is read starting from the namespace keyword the sniff is currently processing. Adds a fixture (strict-types-namespace.php) that combines strict_types with a namespace declaration; the test fails on the current main and passes with this fix. Fixes #319. --- HM/Sniffs/Files/NamespaceDirectoryNameSniff.php | 2 +- HM/Tests/Files/NamespaceDirectoryNameUnitTest.php | 1 + .../inc/standards/strict-types-namespace.php | 5 +++++ 3 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 HM/Tests/Files/NamespaceDirectoryNameUnitTest/inc/standards/strict-types-namespace.php diff --git a/HM/Sniffs/Files/NamespaceDirectoryNameSniff.php b/HM/Sniffs/Files/NamespaceDirectoryNameSniff.php index e6489182..a0a59077 100644 --- a/HM/Sniffs/Files/NamespaceDirectoryNameSniff.php +++ b/HM/Sniffs/Files/NamespaceDirectoryNameSniff.php @@ -30,7 +30,7 @@ public function process( File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); $namespace = ''; - $name_ptr = $phpcsFile->findNext( T_STRING, 0); + $name_ptr = $phpcsFile->findNext( T_STRING, $stackPtr ); if ( ! $name_ptr ) { // Non-namespaced, skip check. return; diff --git a/HM/Tests/Files/NamespaceDirectoryNameUnitTest.php b/HM/Tests/Files/NamespaceDirectoryNameUnitTest.php index c18cad6a..7bb5ef4e 100644 --- a/HM/Tests/Files/NamespaceDirectoryNameUnitTest.php +++ b/HM/Tests/Files/NamespaceDirectoryNameUnitTest.php @@ -51,6 +51,7 @@ public function getErrorList() { 'namespace.php', 'camelcased-namespace.php', 'underscored-namespace.php', + 'strict-types-namespace.php', ]; if ( in_array( $file, $pass, true ) ) { return []; diff --git a/HM/Tests/Files/NamespaceDirectoryNameUnitTest/inc/standards/strict-types-namespace.php b/HM/Tests/Files/NamespaceDirectoryNameUnitTest/inc/standards/strict-types-namespace.php new file mode 100644 index 00000000..80fc3877 --- /dev/null +++ b/HM/Tests/Files/NamespaceDirectoryNameUnitTest/inc/standards/strict-types-namespace.php @@ -0,0 +1,5 @@ +