Web Development
26-07-2024

How to extend PHP code sniffer standards?

Dmytro Tus
Full Stack Web developer

This intruction comes together with github repo, which contains the code example. https://github.com/dmytrotus/phpcs-extending

This implementation was tested and working perfectly on VsCode.

Before implementation

PHP coding standards need to be installed and working.

Change the settings in VsCode


Go to Code -> Preferences -> Settings -> [find: phpcs] -> Phpcs: Standard -> Edit in settings.json
Click on that and change the line

"phpcs.standard": "PSR12"


into 

"phpcs.standard": "~/phpcs-custom/DmytrosCustomCodeStyleStandard/ruleset.xml"

Create ruleset

Create a folder on your local computer. MacOs in my case.

touch ~/phpcs-custom/DmytrosCustomCodeStyleStandard/ruleset.xml

Inside the content of ruleset.xml copy ruleset.xml from root of this repo

The roolset which extends PSR12 standard looks like this

<?xml version="1.0"?>
<ruleset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         name="DmytrosCustomCodeStyleStandard"
         xsi:noNamespaceSchemaLocation="/Users/[your_username]/.composer/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/phpcs.xsd">

    <description>Dmytros custom coding standard extending PSR-12 with additional sniffs.</description>

    <!-- Include PSR-12 ruleset -->
    <rule ref="PSR12"/>

    <!-- Add additional custom rules -->
    <rule ref="DmytrosCustomCodeStyleStandard.Functions.RequireReturnType"/>
    <rule ref="DmytrosCustomCodeStyleStandard.Functions.RequireArgumentType"/>

    <!-- You can also exclude certain PSR-12 rules if needed -->
    <!-- <exclude name="Some.PSR12.Rule"/> -->
</ruleset>

But the same file you can find in github repo.

Create sniffs

Ruleset already extends default PSR12 standards and has 2 additional sniffs
- RequireReturnType
- RequireArgumentType

These sniffs are inside sniffs folder.

Happy Codding. 🥳


Tags:

Another posts