Skip to content

Commit

Permalink
PSR2/NamespaceDeclaration: false positive on namespace operator
Browse files Browse the repository at this point in the history
When the `namespace` keyword was used as an operator, the sniff would incorrectly throw an error too.

Fixed now.

Includes unit test.
  • Loading branch information
jrfnl committed Dec 9, 2020
1 parent cda358f commit deb125a
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Util\Tokens;

class NamespaceDeclarationSniff implements Sniff
{
Expand Down Expand Up @@ -41,6 +42,12 @@ public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();

$nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true);
if ($tokens[$nextNonEmpty]['code'] === T_NS_SEPARATOR) {
// Namespace keyword as operator. Not a declaration.
return;
}

$end = $phpcsFile->findEndOfStatement($stackPtr);
for ($i = ($end + 1); $i < ($phpcsFile->numTokens - 1); $i++) {
if ($tokens[$i]['line'] === $tokens[$end]['line']) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,7 @@ namespace Vendor\

Package;
namespace Vendor\Package;

$call = namespace\function_name();
echo namespace\CONSTANT_NAME;
// Something which is not a blank line.
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,7 @@ namespace Vendor\
Package;

namespace Vendor\Package;

$call = namespace\function_name();
echo namespace\CONSTANT_NAME;
// Something which is not a blank line.

0 comments on commit deb125a

Please sign in to comment.