Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ForbiddenNames: minor tweak to the anonymous classes skip code. #415

Merged
merged 1 commit into from
Apr 27, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 13 additions & 10 deletions Sniffs/PHP/ForbiddenNamesSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -195,12 +195,24 @@ public function processNonString(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $to
return;
}

/*
* Deal with anonymous classes - `class` before a reserved keyword is sometimes
* misidentified as `T_ANON_CLASS`.
* In PHPCS < 2.3.4 these were tokenized as T_CLASS no matter what.
*/
if ($tokens[$stackPtr]['type'] === 'T_ANON_CLASS' || $tokens[$stackPtr]['type'] === 'T_CLASS') {
$prevNonEmpty = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr - 1), null, true);
if ($prevNonEmpty !== false && $tokens[$prevNonEmpty]['type'] === 'T_NEW') {
return;
}
}

/*
* PHP 5.6 allows for use const and use function, but only if followed by the function/constant name.
* - `use function HelloWorld` => move to the next token (HelloWorld) to verify.
* - `use const HelloWorld` => move to the next token (HelloWorld) to verify.
*/
if ($tokens[$stackPtr]['type'] === 'T_USE'
else if ($tokens[$stackPtr]['type'] === 'T_USE'
&& isset($this->validUseNames[strtolower($tokens[$nextNonEmpty]['content'])]) === true
&& $this->supportsAbove('5.6')
) {
Expand Down Expand Up @@ -251,15 +263,6 @@ public function processNonString(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $to
return;
}

// Deal with anonymous classes.
$prevNonEmpty = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr - 1), null, true);
if ($prevNonEmpty !== false
&& $tokens[$prevNonEmpty]['type'] === 'T_NEW'
&& ($tokens[$stackPtr]['type'] === 'T_ANON_CLASS' || $tokens[$stackPtr]['type'] === 'T_CLASS')
) {
return;
}

if ($this->supportsAbove($this->invalidNames[$nextContentLc])) {
$data = array(
$tokens[$nextNonEmpty]['content'],
Expand Down
3 changes: 3 additions & 0 deletions Tests/sniff-examples/forbidden_names_correct_usage.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,3 +154,6 @@ class MyClass4 {

// Functions declared to return by reference.
function &mySayHello() {}

// Anonymous classes.
$a = new class {}