PHPCSStandards / PHP_CodeSniffer

PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.
BSD 3-Clause "New" or "Revised" License
880 stars 54 forks source link

Squiz.Classes.SelfMemberReference: false negative if file contains namespace operator #553

Closed jrfnl closed 1 month ago

jrfnl commented 2 months ago

Describe the bug

The namespace keyword can both be used for namespace declarations as well as as an operator - "magic keyword" - to resolve to the current namespace. See: https://www.php.net/manual/en/language.namespaces.nsconstants.php#example-298

This last case is not correctly taken into account when determining the current namespace, which leads to false negatives.

Code sample

<?php

namespace TestMe;

//namespace\functionCall();

class SelfMemberReference
{
    public function falseNegative()
    {
        $testResults[] = \TestMe\SelfMemberReference::test();
    }
}

To reproduce

Steps to reproduce the behavior:

  1. Create a file called test.php with the code sample above...
  2. Run phpcs -ps ./test.php --standard=squiz --sniffs=squiz.classes.selfmemberreference
  3. See error message displayed
    ------------------------------------------------------------------------------------------------------------------
    FOUND 1 ERROR AFFECTING 1 LINE
    ------------------------------------------------------------------------------------------------------------------
    11 | ERROR | [x] Must use "self::" for local static member reference (Squiz.Classes.SelfMemberReference.NotUsed)
    ------------------------------------------------------------------------------------------------------------------
    PHPCBF CAN FIX THE 1 MARKED SNIFF VIOLATIONS AUTOMATICALLY
    ------------------------------------------------------------------------------------------------------------------
  4. Now uncomment line 5 containing the namespace keyword used as an operator.
  5. Run phpcs -ps ./test.php --standard=squiz --sniffs=squiz.classes.selfmemberreference again.
  6. See no error displayed <= this is the false negative.

Expected behavior

That namespace keywords used as an operator are ignored when determining the applicable namespace name.

Versions (please complete the following information)

Operating System not relevant (Windows 10)
PHP version not relevant (8.3.8)
PHP_CodeSniffer version 3.10.1 / master as of today
Standard Squiz
Install type not relevant (git clone)

Please confirm