Skip to content

Commit

Permalink
Squiz/PostStatementComment: use a different error code for annotations
Browse files Browse the repository at this point in the history
This commit changes `Squiz.Commenting.PostStatementComment` to use a
different error code when an annotation is found. This will allow
ruleset maintainers to selectively exclude the flagging of trailing
annotations from their ruleset. For example, for PHPCS itself, this will
make it possible to use the `// @codeCoverageIgnore` annotation where
needed.

An annotation is defined as any comment that starts with an optional
space, followed by a `@` and any character, as long as it is not a
whitespace. For now, only `//` comments are supported as this is the only
type of comment supported by this sniff.

This change only applies to PHP code as support for JS will be dropped
soon, and JS doesn't seem to follow the same convention of annotations
starting with `@`.
  • Loading branch information
rodrigoprimo committed Oct 11, 2024
1 parent 2e3c58b commit f6053a3
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,14 @@ public function process(File $phpcsFile, $stackPtr)
}
}

if ($phpcsFile->tokenizerType === 'PHP'
&& preg_match('|//\s?@[^\s]+|', $tokens[$stackPtr]['content']) === 1
) {
$error = 'Annotations may not appear after statements';
$phpcsFile->addError($error, $stackPtr, 'AnnotationFound');
return;
}

$error = 'Comments may not appear after statements';
$fix = $phpcsFile->addFixableError($error, $stackPtr, 'Found');
if ($fix === true) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,7 @@ $match = match($foo // comment
) {
1 => 1, // comment
};

$a = 1; // @codeCoverageIgnore
$b = 2; //@phpstan-ignore variable.undefined
$c = 3; // @thisIsNotAnAnnotation - more than one space before the @ symbol.
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,8 @@ $match = match($foo // comment
1 => 1,
// comment
};

$a = 1; // @codeCoverageIgnore
$b = 2; //@phpstan-ignore variable.undefined
$c = 3;
// @thisIsNotAnAnnotation - more than one space before the @ symbol.
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ public function getErrorList($testFile='')
18 => 1,
35 => 1,
53 => 1,
56 => 1,
57 => 1,
58 => 1,
];

case 'PostStatementCommentUnitTest.1.js':
Expand Down

0 comments on commit f6053a3

Please sign in to comment.