How can I suppress PHPCS warnings using comments?

gremo picture gremo · Apr 16, 2013 · Viewed 38.1k times · Source

My TestMyClass.php has two class definitions in the same file (unit testing class), and PHP Code Sniffer complains about each class must be in a file by itself. How can I suppress this warning?

class MyClassImpl implements MyInterface
{
    // ...
}

class MyClassTest extends \PHPUnit_Framework_TestCase
{
    // ...
}

Answer

Greg Sherwood picture Greg Sherwood · Apr 18, 2013

You can get PHP_CodeSniffer to ignore specific files or lines in a file using comments: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Advanced-Usage#ignoring-files-and-folders

In this case, the error will be generated on your second class definition, so you'd have to write you second definition like this:

// @codingStandardsIgnoreStart
class MyClassTest extends \PHPUnit_Framework_TestCase
{
    // @codingStandardsIgnoreEnd
    // ...
}

But you might also choose to just ignore the whole file if it is not supposed to be checked, either using the @codingStandardsIgnoreFile comment or by specifying exclusions on the command line (see the previous link for info).

If you find that you do this a lot and you don't want to add comments to your code, you can also create your own custom coding standard. Assuming you are using the PSR2 standard right now, you'd create an XML file (e.g., mystandard.xml) and include the following content:

<?xml version="1.0"?>
<ruleset name="MyStandard">
 <description>My custom coding standard.</description>
 <rule ref="PSR2" />
 <rule ref="PSR1.Classes.ClassDeclaration.MultipleClasses">
   <severity>0</severity>
 </rule>
</ruleset>

Then run PHP_CodeSniffer like this: phpcs --standard=/path/to/mystandard.xml /path/to/code

Having your own ruleset lets you do a lot of things, including changing error messages, changing the severity or type of a message, including checks from other standards, and setting global ignore rules. More info here: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Annotated-ruleset.xml