Use Php code sniffer (phpcs) to keep code clean with consistent coding style

If you don’t use it already – I would highly recommend it for any new projects, especially if working on a project in a team environment. PHP code sniffer is an essential tool for php developers that helps us with keeping code clean and consistent.

Which PHP coding style to select?

There is only one uniformly recognized PHP coding standard out there – PSR12, which expands and replaces and extends previously used PSR-1/PSR-2.

Most projects/frameworks would likely strive to stay consistent with or base their own styles on it – so this should be good starting point.

If you starting fresh with some PHP application – you might even get phpcs file included already – so just use it or at lest check with your framework guidelines, for example:

Example phpcs configuration file

Here’s the sample php codesniffer configuration file (phpcs.xml) from laminas framework project’s skeleton application:

<?xml version="1.0"?>
<ruleset name="Laminas Coding Standard">
    <description>Laminas Coding Standard</description>

    <!-- display progress -->
    <arg value="p"/>
    <arg name="colors"/>
    <arg name="extensions" value="php,dist,phtml"/>

    <!-- inherit rules from: -->
    <rule ref="PSR12"/>
    <rule ref="Generic.Arrays.DisallowLongArraySyntax"/>
    <rule ref="Generic.Formatting.SpaceAfterNot"/>
    <rule ref="Squiz.WhiteSpace.OperatorSpacing">
        <properties>
            <property name="ignoreNewlines" value="true"/>
        </properties>
    </rule>
    <rule ref="Squiz.WhiteSpace.SuperfluousWhitespace">
        <properties>
            <property name="ignoreBlankLines" value="false"/>
        </properties>
    </rule>
    <rule ref="PSR1.Files.SideEffects">
        <exclude-pattern>public/index.php</exclude-pattern>
    </rule>

    <!-- view files adjustments -->
    <rule ref="Generic.Files.LineLength">
        <exclude-pattern>*.phtml</exclude-pattern>
    </rule>
    <rule ref="PSR12.Files.FileHeader">
        <exclude-pattern>*.phtml</exclude-pattern>
    </rule>

    <!-- Paths to check -->
    <file>config</file>
    <file>module</file>
    <file>public/index.php</file>
</ruleset>

^ everything is fairly self-explanatory.

The most important rule is – <rule ref="PSR12"> which predictably so means – follow PSR12 set of standards and the rest is – just more specific rules, files to include and exclude etc.

Installing PHP Code Sniffer

There are various ways you can install it – as a separate standalone script, through composer or even pear. I tend to favor adding PHP Code Sniffer per-project as a dev-level dependency using composer, as this way its easier to run phpcodesniffer using some specific containerized version of php for example and we don’t have to junk our dev system.

 composer require --dev squizlabs/php_codesniffer

First run

If this is first time you are using php code sniffer on specific project – there will likely be many auto-correctable errors.

Run this command to see all the hints:

linuxdev@hs-dev1:/mnt/480g_drive/projects/crates-project$ ./vendor/bin/phpcs

You are very likely to see a long list of items many of which auto-correctable such as :

...omitted due to excessive length....
FILE: /mnt/480g_drive/projects/crates-project/module/CratesImages/src/Controller/Factory/ViewControllerFactory.php
------------------------------------------------------------------------------------------------------------------
FOUND 3 ERRORS AFFECTING 3 LINES
------------------------------------------------------------------------------------------------------------------
 10 | ERROR | [x] Whitespace found at end of line
 17 | ERROR | [x] Whitespace found at end of line
 20 | ERROR | [x] Expected 1 newline at end of file; 0 found
------------------------------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 3 MARKED SNIFF VIOLATIONS AUTOMATICALLY
------------------------------------------------------------------------------------------------------------------
...omitted due to excessive length....

As you can see from the snippet above phpcs tells us that that all 3 issues are auto-correctable using included PHP Code Beautifier and Fixer (phpcbf) tool. So let’s use it:

linuxdev@hs-dev1:/mnt/480g_drive/projects/crates-project$ ./vendor/bin/phpcbf
FFFFFFFFFFF.F.F.FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF.FFFFFFF.FFFFF  60 / 149 (40%)
FFFFFF..FFFFFFFFFFFFFF.FFFFFFFFFFFF.FFFF...FFFFFFFFFFFFFF..F 120 / 149 (81%)
FFFFFF.FFFFFFF.F.FFFFFFFFFFFF                                149 / 149 (100%)



PHPCBF RESULT SUMMARY
--------------------------------------------------------------------------------------------------------------------------------------
FILE                                                                                                                  FIXED  REMAINING
--------------------------------------------------------------------------------------------------------------------------------------
...
/mnt/480g_drive/projects/crates-project/module/CratesImages/src/Controller/Factory/ViewControllerFactory.php          3      0
...
--------------------------------------------------------------------------------------------------------------------------------------
A TOTAL OF 2816 ERRORS WERE FIXED IN 132 FILES
--------------------------------------------------------------------------------------------------------------------------------------

Time: 4.69 secs; Memory: 20MB

IDE/editor extension

Now that’s great that we can run this script once in a while and get a full list of issues and then correct them using phpcbf . However we probably want to code and be in compliance at all times so it becomes our second nature to follow the coding style as we write code and full scans only reveal infrequent violations.

Many editors/IDEs come with phpcs support out of the box – so make sure to enable it. For extremely popular vscode I use – there is a phpcs plugin that if enabled will read provided phpcs.xml config and simply alert us of coding style violations on the ongoing basis so we can correct them just in time as we type code:

Don’t forget the mental health

There are bigger things in life then coding style or tabs vs spaces debate. Don’t be that one crazy dev on the team that demands every team member to religiously adhere to specific coding style you chose. Soft skills are also very very important part of developer’s live and proper communication and inter-team relationships will likely trump all the coding style zealotry all times every-time.

I have to say – i really like the laravel’s approach to the issue:

https://laravel.com/docs/8.x/contributions#coding-style

Don’t worry if your code styling isn’t perfect! StyleCI will automatically merge any style fixes into the Laravel repository after pull requests are merged. This allows us to focus on the content of the contribution and not the code style.

Hey – instead of annoying the hell out of contributors – why not use something auto-correct lol. Hey – nice take, we might adopt it with our team as well.

Peace. thanks for reading.

Leave a Comment