Setting custom PHP code sniffing rules

Code sniffing is the practice of checking the code for compliance with some pre-determined standards. It’s very important to run your code through a sniffer because it helps with maintenance and ensures better code quality.

The most common standards in PHP are PSR-0, PSR-1, PSR2 and PEAR. These rules might specify details such as depth and type of indentation, placement of braces, spacing, variables names etc. Depending on the standard, they might go into a lot of detail about how the structure of your code should look like.

A popular tool for sniffing code in PHP is the PHP CodeSniffer (phpcs).

When running it it you can add arguments that specify the folder with the files, ignored directories, coding standards etc. When working on different projects for different clients it might be tiresome to have to specify them differently for every sniff. Phpcs lets you create an archive that specify custom rules and arguments to use. Whenever you run phps it will first look into the current directory for the file and if found, apply the configuration.

The file should be be in an xml format. The most useful options that you can specify are:

The file tag adds files and folders to be sniffed.


The “exclude-pattern” tag lets you exclude specific directories or files from sniffing:


The “rule” tag lets you add ruleset by its name and also exclude specific rules if you would not like to apply them:

<rule ref="PEAR">
   <exclude name="PEAR.NamingConventions.ValidFunctionName"/>

The arg tag lets you specify arguments that should be passed to the phpcs executable, just like the arguments from the command line. The names and acceptable values are sames as on the CLI, with a couple of arguments not permitted to be used there.

 <arg name="basepath" value="."/>

Using custom ruleset files is very useful when you would like to track the quality of your code and your projects must conform to different standard. Defining them before starting a project will surely help you produce cleaner code.