DEV Community

Cover image for How to add PHP CS Fixer to your project?
Richard Dobroň
Richard Dobroň

Posted on

2 1

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
Enter fullscreen mode Exit fullscreen mode

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",
}
}
view raw composer.json hosted with ❤ by GitHub

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
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay