Skip to content

NamespaceDirectoryNameSniff suggests strict_types in a subdirectory's file. #319

@costdev

Description

@costdev

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);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions