Apr 20, 2019 by Thibault Debatty | 23110 views
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...
Nothing difficult here, just use composer:
composer require --dev squizlabs/php_codesniffer
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 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:
You can now run the test simply typing
./vendor/bin/phpcs
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