4

Install PHP code sniffer fixer in a Laravel project

 2 years ago
source link: https://dev.to/arielmejiadev/install-php-code-sniffer-fixer-in-a-laravel-project-32ha
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Code sniffer is a package to apply syntax rules to our php code to follow PSR-standards, here a guide to install and use it:

Install code sniffer

composer require friendsofphp/php-cs-fixer
Enter fullscreen modeExit fullscreen mode

Add a configuration file

touch .php-cs-fixer.php
Enter fullscreen modeExit fullscreen mode

You can add your configuration rules, here a good example to use it in a laravel projects:

<?php

$finder = PhpCsFixer\Finder::create()
    ->in(__DIR__)
    ->exclude(['bootstrap', 'storage', 'vendor'])
    ->name('*.php')
    ->name('_ide_helper')
    ->notName('*.blade.php')
    ->ignoreDotFiles(true)
    ->ignoreVCS(true);

$config = new PhpCsFixer\Config();
return $config->setRules([
    '@PSR2' => true,
    'array_syntax' => ['syntax' => 'short'],
    'ordered_imports' => ['sort_algorithm' => 'alpha'],
    'no_unused_imports' => true,
])
    ->setUsingCache(false)
    ->setFinder($finder);
Enter fullscreen modeExit fullscreen mode

Execute the code sniffer fixer

On terminal execute this command:

vendor/bin/php-cs-fixer fix
Enter fullscreen modeExit fullscreen mode

You can add more flags to customize the behavior of the fixer, here another example:

vendor/bin/php-cs-fixer fix --allow-risky=yes --dry-run --verbose
Enter fullscreen modeExit fullscreen mode

You can install husky with npm to fire this commands on husky hooks and execute any of this commands automatically, this is all thanks for reading.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK