Set up php-cs-fixer in PHPStorm
1 min read

Set up php-cs-fixer in PHPStorm

Set up php-cs-fixer in PHPStorm.
Set up php-cs-fixer in PHPStorm

If you want to automatically fix the code style in Phpstorm using php-cs-fixer, create a configuration file inside your project folder, name it - .php_cs.dist

Then, copy paste this code:

<?php
$config = PhpCsFixer\Config::create()
    ->setRiskyAllowed(true)
    ->setRules([
        '@PSR2' => true,
        '@Symfony' => true,
        'phpdoc_align' => true,
        'no_superfluous_phpdoc_tags' => false,
        'binary_operator_spaces' => ['align_double_arrow' => true],
        'yoda_style' => false,
        'single_line_throw' => false,
        'visibility_required' => ['property', 'method', 'const'],
        'list_syntax' => ['syntax' => 'short'],
        'array_syntax' => ['syntax' => 'short'],
    ])
    ->setFinder(
        PhpCsFixer\Finder::create()->in(__DIR__)
    )
;
try {
    PhpCsFixer\FixerFactory::create()
        ->registerBuiltInFixers()
        ->registerCustomFixers($config->getCustomFixers())
        ->useRuleSet(new PhpCsFixer\RuleSet($config->getRules()));
} catch (PhpCsFixer\ConfigurationException\InvalidConfigurationException $e) {
    $config->setRules([]);
} catch (UnexpectedValueException $e) {
    $config->setRules([]);
}
return $config;
I use this configuration on a daily basis.

As you can see, there is a list of rules like: @PSR2, list_syntax, etc. You can add your own rules or use the predefined ones, if you want more information - take a look here.

Next, go to: File -> Settings -> Tools -> External Tools

click - Add new

And fill these lines:

  • Program:  /path-to-php-cs-fixer/bin/php-cs-fixer
  • Arguments: --verbose --config=/path-to-config-file/.php_cs.dist fix "$FileDir$/$FileName$"
  • Working directory: $ProjectFileDir$

One more thing, you need to add key binding for a new command. Go to File -> Settings -> Keymap: (Search by the name of your external tool). In my case, it's a csfixer.

That's it; now you can use it.

Open any PHP file and use your key binding - it will fix your code according to your configuration.