phpcs-cognitive-complexity icon indicating copy to clipboard operation
phpcs-cognitive-complexity copied to clipboard

Improve sniff implementation to be code style agnostic

Open Rarst opened this issue 5 years ago • 1 comments

Extracted from #1

Sniff code:

  • $method: you are presuming a code style. Best practice sniffs should be code style agnostic. While not very common, this will break on:
public function // some comment
   functionName() {}

Analyzer code:

  • $nextToken in isIncrementingToken() is not code style agnostic.

I am bad with parsers and have no idea how to approach it, so this might take a while. 😅

Rarst avatar Feb 19 '20 08:02 Rarst

@Rarst Hopefully this will help:

Never presume code-style and do things like ($stackPtr + 1) if you want to examine the next effective token. Always use findNext()/findPrevious() in combination with Tokens::$emptyTokens instead. That will disregard whitespace, comment and PHPCS native whitelist comments (which have a separate token).

As for the above:

To get the name of a function based on the T_FUNCTION token - use $phpcsFile->getDeclarationName(). That function exists for a reason ;-)

To get the next effective token in isIncrementingToken():

$nextToken = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true);
if ($nextToken === false || $tokens[$nextToken]['code'] !== T_SEMICOLON) {
    return true;
}

jrfnl avatar Feb 19 '20 09:02 jrfnl