Skip to content

Commit

Permalink
Squiz/BlockComment: prevent false positives with attributes
Browse files Browse the repository at this point in the history
PHP 8.0+ attributes can be placed between a docblock and the function/class declaration it applies to.

The `Squiz.Commenting.BlockComment` sniff did not yet take this into account when determining whether a comment was a docblock or an block comment incorrectly using the docblock syntax.

This would result in false positive `Block comments must be started with /*` errors.

Fixed now.
  • Loading branch information
jrfnl committed Jul 23, 2021
1 parent d5c1cf7 commit 39dd4b7
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/Standards/Squiz/Sniffs/Commenting/BlockCommentSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,18 @@ public function process(File $phpcsFile, $stackPtr)
// If this is a function/class/interface doc block comment, skip it.
// We are only interested in inline doc block comments.
if ($tokens[$stackPtr]['code'] === T_DOC_COMMENT_OPEN_TAG) {
$nextToken = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true);
$ignore = [
$nextToken = $stackPtr;
do {
$nextToken = $phpcsFile->findNext(Tokens::$emptyTokens, ($nextToken + 1), null, true);
if ($tokens[$nextToken]['code'] === T_ATTRIBUTE) {
$nextToken = $tokens[$nextToken]['attribute_closer'];
continue;
}

break;
} while (true);

$ignore = [
T_CLASS => true,
T_INTERFACE => true,
T_TRAIT => true,
Expand Down
16 changes: 16 additions & 0 deletions src/Standards/Squiz/Tests/Commenting/BlockCommentUnitTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -272,3 +272,19 @@ $contentToEcho
* No blank line allowed above the comment if it's the first non-empty token after a PHP open tag.
*/
$contentToEcho

/**
* Comment should be ignored, even though there is an attribute between the docblock and the class declaration.
*/

#[AttributeA]

final class MyClass
{
/**
* Comment should be ignored, even though there is an attribute between the docblock and the function declaration
*/
#[AttributeA]
#[AttributeB]
final public function test() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -274,3 +274,19 @@ $contentToEcho
* No blank line allowed above the comment if it's the first non-empty token after a PHP open tag.
*/
$contentToEcho

/**
* Comment should be ignored, even though there is an attribute between the docblock and the class declaration.
*/

#[AttributeA]

final class MyClass
{
/**
* Comment should be ignored, even though there is an attribute between the docblock and the function declaration
*/
#[AttributeA]
#[AttributeB]
final public function test() {}
}

0 comments on commit 39dd4b7

Please sign in to comment.