coding-standards icon indicating copy to clipboard operation
coding-standards copied to clipboard

NamespaceDirectoryNameSniff suggests `strict_types` in a subdirectory's file.

Open costdev opened this issue 3 months ago • 0 comments

Overview

When strict_types is declared in a subdirectory's namespaced file, NamespaceDirectoryNameSniff reports the NameMismatch error and recommends strict_types as the namespace and the directory name.

Reproduction

Test file: inc/subdir/class-test.php Test code:

<?php

declare(strict_types=1);

namespace MyNamespace\Subdir;

Test command:

./vendor/bin/phpcs --sniffs=HM.Files.NamespaceDirectoryName inc/subdir/class-test.php

Command result:

Directory subdir for namespace strict_types found; use strict_types instead

Cause

File: HM/Sniffs/Files/NamespaceDirectoryNameSniff.php Ref Line: 33

$name_ptr = $phpcsFile->findNext( T_STRING, 0);

0 begins the search from the beginning of the file, not from where T_NAMESPACE was detected. The first T_STRING is strict_types.

Workarounds

In PHP, the strict_types declaration must be the first statement in the script or a Fatal Error will be thrown, so this is not avoidable by rearranging line positions.

Therefore, the workarounds are:

  • Don't namespace a file that declares strict_types, OR
  • Don't declare strict_types in a namespaced file.

Solution

The solution is straightforward:

Change 0 to $stackPtr so the search begins from where T_NAMESPACE was detected:

$name_ptr = $phpcsFile->findNext( T_STRING, $stackPtr);

costdev avatar Oct 25 '25 16:10 costdev