Friday 3 July 2009

Suppress error and warning messages in PHP_CodeSniffer

Just over 13 months ago, I had a feature request submitted for PHP_CodeSniffer to allow developers to annotate their code with comments that tell PHP_CodeSniffer to ignore some lines. At the time, I remember thinking "This is a hack!", but I've changed my mind. PHP_CodeSniffer version 1.2.0 will have error message suppression comment tags.

You use them like so:

$var = TRUE;
// @codingStandardsIgnoreStart
if ($var === true) {
echo "true that";
}
// @codingStandardsIgnoreEnd

If you use the Squiz coding standard that comes bundled with PHP_CodeSniffer, it will complain about pretty much everything and tell you you can't have "true" in lowercase and that echo'd string can't be in double quotes.

Without the new suppression tags in place, you get this:
FILE: /Users/gsherwood/PHP_CodeSniffer/temp.php
---------------------------------------------------------------
FOUND 3 ERROR(S) AND 0 WARNING(S) AFFECTING 3 LINE(S)
---------------------------------------------------------------
2 | ERROR | Missing file doc comment
4 | ERROR | TRUE, FALSE and NULL must be uppercase; expected
| | "TRUE" but found "true"
5 | ERROR | String "true that" does not require double quotes;
| | use single quotes instead
---------------------------------------------------------------

With them in place, you get this:
FILE: /Users/gsherwood/PHP_CodeSniffer/temp.php
---------------------------------------------------------------
FOUND 1 ERROR(S) AND 0 WARNING(S) AFFECTING 1 LINE(S)
---------------------------------------------------------------
2 | ERROR | Missing file doc comment
---------------------------------------------------------------

Too easy. Sorry it took so long.

Please don't be tempted to wrap your entire file in these tags. The Squiz standard will still find ways to yell at you and you're not fooling anyone.

Grab the code from CVS now or wait for the next release, which will be whenever I get my act together.