How can I suppress PHPCS warnings using comments?

With the following comments you can ignore whatever part of a file you would like.

Ignore all the sniffs for the file:

<?php
// phpcs:ignoreFile

Ignore only the current and next line:

// phpcs:ignore
public function store($myArray)

Ignore the current line:

public function store($myArray) // phpcs:ignore

Ignore a certain amount of lines in a file:

// phpcs:disable
public function store($myArray): void
{
    if (count($myArray) > 3) {
        // Humongous amount of legacy code you don't want to look at
    }

    return;
}
// phpcs:enable

With // phpcs:ignore and // phpcs:disable you can also specify which messages, sniffs, categories or standards you would like to disable, for example:

// phpcs:ignore Squiz.Arrays.ArrayDeclaration.SingleLineNotAllowed
$foo = [1,2,3];

If you want to read more about this subject, you can visit the wiki. Some of the examples were taken from there.


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


The @codingStandards syntax is deprecated as of version 3.2.0, use phpcs instead.

Some examples:

// phpcs:disable
// phpcs:ignore
// phpcs:enable

See this page for more information: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Advanced-Usage#ignoring-parts-of-a-file

Tags:

Php

Phpunit

Phpcs