Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore some errors or warnings in PHP_CodeSniffer

Tags:

php

I'm using PHP_CodeSniffer to analyse my php code. The problem is that the code of my applications is quite complex (about 10,000 files) and it is a bit old (about 15 years) so it follows no standards like PSR.
That's the reason why CodeSniffer produces very large reports. Because it takes too much time to fix all "problems", I'm thinking about to ignore some things, f.e.

Class name must begin with a capital letter

or

Opening brace of a class must be on the line after the definition

Is there a way to tell CodeSniffer to ignore such errors when creating the report?

like image 386
altralaser Avatar asked Mar 05 '23 18:03

altralaser


2 Answers

To disable/re-enable entire coding standard or specific sniffs for just a given fragment of code - use some special comments

// phpcs:disable Generic.Commenting.Todo.Found
$xmlPackage = new XMLPackage;
$xmlPackage['error_code'] = get_default_error_code_value();
// TODO: Add an error message here.
$xmlPackage->send();
// phpcs:enable

or

// phpcs:disable PEAR,Squiz.Arrays
$foo = [1,2,3];
bar($foo,true);
// phpcs:enable PEAR.Functions.FunctionCallSignature
bar($foo,false);
// phpcs:enable

Note: All phpcs:disable and phpcs:enable comments only apply to the file they are contained within. After the file has finished processing all sniffs are re-enabled for future files.

You can also ignore a single line using the phpcs:ignore comment. This comment will ignore the line that the comment is on, and the following line.

// phpcs:ignore
$foo = [1,2,3];
bar($foo, false);

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

If you want to only check your files for a small list of sniffs you can specify them on the command line

$ phpcs --standard=PEAR --sniffs=Generic.PHP.LowerCaseConstant,PEAR.WhiteSpace.ScopeIndent /path/to/code

Or you can run the whole coding standard and exclude a small list of sniffs

$ phpcs --standard=PEAR --exclude=Generic.PHP.LowerCaseConstant,PEAR.WhiteSpace.ScopeIndent /path/to/code
like image 77
IVO GELOV Avatar answered Mar 08 '23 23:03

IVO GELOV


You will need to create your own ruleset. Here's info on available options: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Annotated-ruleset.xml and here you can find how to create such: https://ncona.com/2012/12/creating-your-own-phpcs-standard/

You can copy existing one (like PSR2) and adjust it to your needs.

On github of codesniffer project you can find PSR2 ruleset: https://github.com/squizlabs/PHP_CodeSniffer/blob/master/src/Standards/PSR2/ruleset.xml

like image 44
matiit Avatar answered Mar 08 '23 22:03

matiit