Set up php-cs-fixer in PHPStorm

Updated: 13.07.2023

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-fixer.dist.php

Then, copy and paste this code:

<?php
$finder = (new PhpCsFixer\Finder())
    ->in(__DIR__)
    ->exclude('var')
;

return (new PhpCsFixer\Config())
    ->setRules([
        '@PER' => true,
        '@Symfony' => true,
// other rules
    ])
    ->setFinder($finder)
;

I use this configuration daily.

As you can see, there is a list of rules: @PER, @Symfony, etc. You can add more rules, here you can find a list of rules

Next, in PhpStorm 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 .php-cs-fixer.dist.php fix "$FileDir$/$FileName$"
  • Working directory: $ProjectFileDir$

One more thing, you need to add a 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.

If you are using PHP 8.2+ and you see an error like this:

PHP needs to be a minimum version of PHP 7.4.0 and maximum version of PHP 8.1.*.

Do this:
create a new file in ./bin directory of your project name it cs-fixer and copy and paste this code:

#!/usr/bin/env php
<?php

putenv('PHP_CS_FIXER_IGNORE_ENV=1');
include __DIR__ . '/../vendor/bin/php-cs-fixer';

And go to File -> Settings -> Tools -> External Tools , select your external tool, and replace Program to your-project-path/bin/cs-fixer

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.