How to use PHP Code Sniffer

How to use PHP Code Sniffer

This blog post will explain how to set up a PHP project to use a PHP code sniffer to ensure code conventions are correctly used in a project.
I will be using PHP_CodeSniffer and installing it using Composer.

The first thing to do is to create a composer.json file. In this file, you should include the code sniffer as a dependency as shown:

{
    "require-dev": {
        "squizlabs/php_codesniffer": "3.*"
    }
}

Next, you can install this dependancy:

composer install

Now that the package is installed, you need to create a ruleset.xml file that will define the coding conventions that should be enforced by the code sniffer. So, create a file called ruleset.xml and you can use the following example ruleset file:

<?xml version="1.0"?>
<ruleset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="PSR12" xsi:noNamespaceSchemaLocation="../../../phpcs.xsd">
    <description>Example Code Convention Rules</description>
    <arg name="tab-width" value="4"/>
    <file>.</file>
    <exclude-pattern>*/vendor/*</exclude-pattern>
    <rule ref="PSR12"/>
    <rule ref="Generic.Files.LineLength">
        <properties>
            <property name="lineLimit" value="140"/>
        </properties>
    </rule>
</ruleset>

Now that you have installed the code sniffer and defined the ruleset, you can use the code sniffer be executing the following command:

phpcs --standard=ruleset.xml

This command will output any issues the code sniffer found. Here is an example of its output:

Screenshot from 2022-01-15 13-38-32.png

The issues the code sniffer found marked with a [X] can be fixed automatically by executing this command:

phpcbf --standard=ruleset.xml

All of the code used in this demonstration can be found here: github.com/DamienCahill/php-tests-and-sniff..

The advantages of using a code sniffer are

Leads to consistent code, making it potentially easier to read

Prevent code smells by enforcing maximum line lengths

Some issues can be automatically fixed so time can be saved

The documentation for the code sniffer used can be found here.

Did you find this article valuable?

Support Damien Cahill by becoming a sponsor. Any amount is appreciated!