Written By
Views

How to add PHP CS Fixer to your project?

How to add PHP CS Fixer to your project?

First of all, add PHP CS Fixer to your project:

composer require --dev friendsofphp/php-cs-fixer

A configuration file called .php-cs-fixer.dist.php needs to be in the root directory of your project if you want to avoid command-line options.

There are many rules that can be set, I usually use these. It follows the PSR12 code standards and checks both the src and tests directories.

<?php

$finder = Symfony\Component\Finder\Finder::create()
    ->in([
        __DIR__ . '/src',
        __DIR__ . '/tests',
    ])
    ->name('*.php')
    ->ignoreDotFiles(true)
    ->ignoreVCS(true);

return (new PhpCsFixer\Config())
    ->setRules([
        '@PSR12' => true,
        'array_syntax' => ['syntax' => 'short'],
        'ordered_imports' => ['sort_algorithm' => 'alpha'],
        'no_unused_imports' => true,
        'not_operator_with_successor_space' => true,
        'trailing_comma_in_multiline' => true,
        'phpdoc_scalar' => true,
        'unary_operator_spaces' => true,
        'binary_operator_spaces' => true,
        'blank_line_before_statement' => [
            'statements' => ['break', 'continue', 'declare', 'return', 'throw', 'try'],
        ],
        'phpdoc_single_line_var_spacing' => true,
        'phpdoc_var_without_name' => true,
        'class_attributes_separation' => [
            'elements' => [
                'method' => 'one',
            ],
        ],
        'braces' => [
            'allow_single_line_closure' => true,
            'position_after_anonymous_constructs' => 'same',
            'position_after_functions_and_oop_constructs' => 'next',
            'position_after_control_structures' => 'same',
        ],
        'method_argument_space' => [
            'on_multiline' => 'ensure_fully_multiline',
            'keep_multiple_spaces_after_comma' => true,
        ],
        'single_trait_insert_per_statement' => true,
    ])
    ->setFinder($finder);

You can find more rules in the PHP CS Fixer docs.

Let’s add a some scripts to composer.json file:

{
    ...
    "scripts": {
        "fix-style": "vendor/bin/php-cs-fixer fix --allow-risky=yes",
        "check-style": "vendor/bin/php-cs-fixer fix --allow-risky=yes --dry-run",
    }
}

Now, just run composer run fix-style and all your code style errors will be fixed.

The --dry-run flag will run the fixer without making changes to your files.

If you are using Git, add .php-cs-fixer.cache (this is the cache file created by php-cs-fixer) to .gitignore:

.php-cs-fixer.cache

Comments (0)

loading comments