How to use PHP CS Fixer ruleset with Easy Coding Standard (ECS)


This post is a quick guide on how to use the @Symfony ruleset from PHP CS Fixer with Easy Coding Standard, since this ruleset is not shipped anymore with ECS.

What is Easy Coding Standard?

Easy Coding Standard is a tool that helps you to check your code against PHP coding standards.

The main advantage of Easy Coding Standard is that it wraps PHP CS Fixer and PHP_CodeSniffer to provide a unified interface for both tools, meaning that you can easily use both tools with the same configuration file and a single command.

It also comes with some ruleset out of the box, and even if they are great, there is no Symfony related ruleset anymore, so we need to find a way to use the @Symfony ruleset from PHP CS Fixer.

Using PHP CS Fixer ruleset with Easy Coding Standard

Assuming that you already have Easy Coding Standard installed and configured through the following commands:

1composer require --dev symplify/easy-coding-standard
2./vendor/bin/ecs

You will need to update your ecs.php configuration file to use the FixerFactory and RuleSet classes from PHP CS Fixer, and manually register PHP CS Fixer fixers through the ECSConfig#rule and ECSConfig#ruleWithConfiguration methods:

ecs.php
 1<?php
 2
 3declare(strict_types=1);
 4
 5use PhpCsFixer\FixerFactory;
 6use PhpCsFixer\RuleSet\RuleSet;
 7use Symplify\EasyCodingStandard\Config\ECSConfig;
 8
 9return function (ECSConfig $ecsConfig): void {
10    $ecsConfig->paths([
11        __DIR__ . '/src',
12        __DIR__ . '/tests',
13    ]);
14
15     // Configure Symfony and Symfony Risky SetList from PHP-CS-Fixer, since they are not shipped anymore with Easy Coding Standard.
16    $fixerFactory = new FixerFactory();
17    $fixerFactory->registerBuiltInFixers();
18    $fixerFactory->useRuleSet($ruleSet = new RuleSet([
19        '@Symfony' => true,
20        // You can also enable the risky ruleset if you want.
21        //'@Symfony:risky' => true,
22    ]));
23
24    foreach ($fixerFactory->getFixers() as $fixer) {
25        if (null !== $fixerConfiguration = $ruleSet->getRuleConfiguration($fixer->getName())) {
26            $ECSConfig->ruleWithConfiguration($fixer::class, $fixerConfiguration);
27        } else {
28            $ECSConfig->rule($fixer::class);
29        }
30    }
31};

And voilà! You can now run Easy Coding Standard with the Symfony ruleset from PHP CS Fixer.