Using PHP CodeSniffer in a Laravel project

Apr 20, 2019 by Thibault Debatty | 23110 views

Laravel

https://cylab.be/blog/22/using-php-codesniffer-in-a-laravel-project

PHP CodeSniffer is a great tool that enforces everybody is using the same coding standard when contributing to a project. For a Laravel project, there are however a few caveats to handle...

Installing

Nothing difficult here, just use composer:

composer require --dev squizlabs/php_codesniffer

Testing

You can now run a first test by typing:

./vendor/bin/phpcs ./app

This will run PHP CodeSniffer for every file in the app directory, and it will generate A LOT of errors because:

  • by default PHP CodeSniffer assumes you are using the PEAR coding standard while Laravel uses PSR2
  • a lot of Laravel files do not follow a predefined coding standard, like cache files, blade views, composer autoloader etc..

PHP CodeSniffer

Configuring

By default, PHP CodeSniffer looks for a file called phpcs.xml to use as configuration. Hence, to use PHP CodeSniffer with Laravel, you should create phpcs.xml at the root of your project, with following content:

<?xml version="1.0"?>
<ruleset name="PHP_CodeSniffer">
    <description>The coding standard for our project.</description>
    <rule ref="PSR2"/>

    <file>app</file>
    <file>bootstrap</file>
    <file>config</file>
    <file>database</file>
    <file>resources</file>
    <file>routes</file>
    <file>tests</file>

    <exclude-pattern>bootstrap/cache/*</exclude-pattern>
    <exclude-pattern>bootstrap/autoload.php</exclude-pattern>
    <exclude-pattern>*/migrations/*</exclude-pattern>
    <exclude-pattern>*/seeds/*</exclude-pattern>
    <exclude-pattern>*.blade.php</exclude-pattern>
    <exclude-pattern>*.js</exclude-pattern>

    <!-- Show progression -->
    <arg value="p"/>
</ruleset>

This configuration file indicates:

  • that the standard to use is PSR2
  • the directories to analyze
  • the files to exclude

You can now run the test simply typing

./vendor/bin/phpcs

Fixing

PHP CodeSniffer has built-in tool that can fix a lot of the style errors: phpcbf (PHP Code Beautifier and Fixer). With your configuration file phpcs.xml, you can fix your code by simply typing

./vendor/bin/phpcbf

This blog post is licensed under CC BY-SA 4.0

This website uses cookies. More information about the use of cookies is available in the cookies policy.
Accept