Question

It is possible to ignore some parts of code from a php file when it's analyzed by PHP_CodeSniffer?

Was it helpful?

Solution

Yes it is possible with @codingStandardsIgnoreStart and @codingStandardsIgnoreEnd annotations

<?php
some_code();
// @codingStandardsIgnoreStart
this_will_be_ignored();
// @codingStandardsIgnoreEnd
some_other_code();

It is also described in the documentation.

OTHER TIPS

You can either use the combination: @codingStandardsIgnoreStart and @codingStandardsIgnoreEnd or you can use @codingStandardsIgnoreLine.

Example:

<?php

command1();
// @codingStandardsIgnoreStart
command2(); // this line will be ignored by Codesniffer
command3(); // this one too
command4(); // this one too
// @codingStandardsIgnoreEnd

command6();

// @codingStandardsIgnoreLine
command7(); // this line will be ignored by Codesniffer

Before version 3.2.0, PHP_CodeSniffer used different syntax for ignoring parts of code from file. See the Anti Veeranna's and Martin Vseticka's answers. The old syntax will be removed in version 4.0

PHP_CodeSniffer is now using // phpcs:disable and // phpcs:enable comments to ignore parts of files and // phpcs:ignore to ignore one line.

Now, it is also possible to only disable or enable specific error message codes, sniffs, categories of sniffs, or entire coding standards. You should specify them after comments. If required, you can add a note explaining why sniffs are being disable and re-enabled by using the -- separator.

<?php

/* Example: Ignoring parts of file for all sniffs */
$xmlPackage = new XMLPackage;
// phpcs:disable
$xmlPackage['error_code'] = get_default_error_code_value();
$xmlPackage->send();
// phpcs:enable

/* Example: Ignoring parts of file for only specific sniffs */
// 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

/* Example: Ignoring next line */
// phpcs:ignore
$foo = [1,2,3];
bar($foo, false);

/* Example: Ignoring current line */
$foo = [1,2,3]; // phpcs:ignore
bar($foo, false);

/* Example: Ignoring one line for only specific sniffs */
// phpcs:ignore Squiz.Arrays.ArrayDeclaration.SingleLineNotAllowed
$foo = [1,2,3];
bar($foo, false);

/* Example: Optional note */ 
// phpcs:disable PEAR,Squiz.Arrays -- this isn't our code
$foo = [1,2,3];
bar($foo,true);
// phpcs:enable PEAR.Functions.FunctionCallSignature -- check function calls again
bar($foo,false);
// phpcs:enable -- this is out code again, so turn everything back on

For more details see PHP_CodeSniffer's documentation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top