Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
96.72% covered (success)
96.72%
59 / 61
80.00% covered (warning)
80.00%
4 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
ECSConfig
96.72% covered (success)
96.72%
59 / 61
80.00% covered (warning)
80.00%
4 / 5
13
0.00% covered (danger)
0.00%
0 / 1
 configure
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 applyDefaultPathsAndSkips
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 applyDefaultRulesAndSets
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
2
 applyPhpCsFixerSets
100.00% covered (success)
100.00%
32 / 32
100.00% covered (success)
100.00%
1 / 1
4
 phpdocTagFixers
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
4.59
1<?php
2
3declare(strict_types=1);
4
5/**
6 * Fast Forward Development Tools for PHP projects.
7 *
8 * This file is part of fast-forward/dev-tools project.
9 *
10 * @author   Felipe SayĆ£o Lobato Abreu <github@mentordosnerds.com>
11 * @license  https://opensource.org/licenses/MIT MIT License
12 *
13 * @see      https://github.com/php-fast-forward/
14 * @see      https://github.com/php-fast-forward/dev-tools
15 * @see      https://github.com/php-fast-forward/dev-tools/issues
16 * @see      https://php-fast-forward.github.io/dev-tools/
17 * @see      https://datatracker.ietf.org/doc/html/rfc2119
18 */
19
20namespace FastForward\DevTools\Config;
21
22use FastForward\DevTools\Path\WorkingProjectPathResolver;
23use PhpCsFixer\Fixer\Import\GlobalNamespaceImportFixer;
24use PhpCsFixer\Fixer\Phpdoc\GeneralPhpdocAnnotationRemoveFixer;
25use PhpCsFixer\Fixer\Phpdoc\PhpdocAlignFixer;
26use PhpCsFixer\Fixer\Phpdoc\NoEmptyPhpdocFixer;
27use PhpCsFixer\Fixer\Phpdoc\NoSuperfluousPhpdocTagsFixer;
28use PhpCsFixer\Fixer\Phpdoc\PhpdocAddMissingParamAnnotationFixer;
29use PhpCsFixer\Fixer\Phpdoc\PhpdocNoEmptyReturnFixer;
30use PhpCsFixer\Fixer\Phpdoc\PhpdocToCommentFixer;
31use PhpCsFixer\Fixer\PhpUnit\PhpUnitTestCaseStaticMethodCallsFixer;
32use PhpCsFixer\FixerFactory;
33use PhpCsFixer\RuleSet\RuleSet;
34use Symplify\CodingStandard\Fixer\Annotation\RemoveMethodNameDuplicateDescriptionFixer;
35use Symplify\CodingStandard\Fixer\Annotation\RemovePHPStormAnnotationFixer;
36use Symplify\CodingStandard\Fixer\Annotation\RemovePropertyVariableNameDescriptionFixer;
37use Symplify\CodingStandard\Fixer\ArrayNotation\ArrayListItemNewlineFixer;
38use Symplify\CodingStandard\Fixer\ArrayNotation\ArrayOpenerAndCloserNewlineFixer;
39use Symplify\CodingStandard\Fixer\Commenting\AddMissingParamNameFixer;
40use Symplify\CodingStandard\Fixer\Commenting\AddMissingVarNameFixer;
41use Symplify\CodingStandard\Fixer\Commenting\DoubleAsteriskInlineVarFixer;
42use Symplify\CodingStandard\Fixer\Commenting\FixParamNameTypoFixer;
43use Symplify\CodingStandard\Fixer\Commenting\RemoveDeadParamFixer;
44use Symplify\CodingStandard\Fixer\Commenting\RemoveParamNameReferenceFixer;
45use Symplify\CodingStandard\Fixer\Commenting\RemoveSuperfluousReturnNameFixer;
46use Symplify\CodingStandard\Fixer\Commenting\RemoveSuperfluousVarNameFixer;
47use Symplify\CodingStandard\Fixer\Commenting\SingleLineInlineVarDocBlockFixer;
48use Symplify\CodingStandard\Fixer\Commenting\SwitchedTypeAndNameFixer;
49use Symplify\CodingStandard\Fixer\Commenting\RemoveUselessDefaultCommentFixer;
50use Symplify\CodingStandard\Fixer\LineLength\LineLengthFixer;
51use Symplify\CodingStandard\Fixer\Spacing\MethodChainingNewlineFixer;
52use Symplify\CodingStandard\Fixer\Spacing\SpaceAfterCommaHereNowDocFixer;
53use Symplify\CodingStandard\Fixer\Spacing\StandaloneLinePromotedPropertyFixer;
54use Symplify\CodingStandard\Fixer\Strict\BlankLineAfterStrictTypesFixer;
55use Symplify\EasyCodingStandard\Config\ECSConfig as ECSConfigInterface;
56use Symplify\EasyCodingStandard\Configuration\ECSConfigBuilder;
57use function Safe\getcwd;
58
59/**
60 * Provides the default ECS configuration.
61 *
62 * Consumers can use this as a starting point and extend it:
63 *
64 *     $config = \FastForward\DevTools\Config\ECSConfig::configure();
65 *     $config->withRules([CustomRule::class]);
66 *     $config->withConfiguredRule(PhpdocAlignFixer::class, ['align' => 'vertical']);
67 *     return $config;
68 *
69 * @see https://github.com/symplify/easy-coding-standard
70 */
71 class ECSConfig
72{
73    /**
74     * @var array{symfony: bool, symfonyRisky: bool, auto: bool, autoRisky: bool} the PHP-CS-Fixer sets applied by default
75     */
76    public const array DEFAULT_PHP_CS_FIXER_SETS = [
77        'symfony' => true,
78        'symfonyRisky' => true,
79        'auto' => true,
80        'autoRisky' => true,
81    ];
82
83    /**
84     * @var array{psr12: bool, common: bool, symplify: bool, cleanCode: bool} the prepared ECS sets applied by default
85     */
86    public const array DEFAULT_PREPARED_SETS = [
87        'psr12' => true,
88        'common' => true,
89        'symplify' => true,
90        'cleanCode' => true,
91    ];
92
93    /**
94     * @var list<class-string> the ECS/CS Fixer rules that SHOULD be skipped by default
95     */
96    public const array DEFAULT_SKIPPED_RULES = [
97        PhpdocToCommentFixer::class,
98        NoSuperfluousPhpdocTagsFixer::class,
99        NoEmptyPhpdocFixer::class,
100        PhpdocNoEmptyReturnFixer::class,
101        GlobalNamespaceImportFixer::class,
102        GeneralPhpdocAnnotationRemoveFixer::class,
103    ];
104
105    /**
106     * @var array<class-string, array<string, mixed>> the configured ECS rules applied by default
107     */
108    public const array DEFAULT_CONFIGURED_RULES = [
109        PhpdocAlignFixer::class => [
110            'align' => 'left',
111        ],
112        PhpUnitTestCaseStaticMethodCallsFixer::class => [
113            'call_type' => 'self',
114        ],
115        PhpdocAddMissingParamAnnotationFixer::class => [
116            'only_untyped' => false,
117        ],
118    ];
119
120    /**
121     * @var list<class-string> successors of ECS's bundled malformed PHPDoc-tag fixer
122     * @see https://github.com/ecsphp/ecs-src/pull/334
123     */
124    private const array PHPDOC_TAG_FIXERS = [
125        AddMissingParamNameFixer::class,
126        AddMissingVarNameFixer::class,
127        DoubleAsteriskInlineVarFixer::class,
128        FixParamNameTypoFixer::class,
129        RemoveDeadParamFixer::class,
130        RemoveParamNameReferenceFixer::class,
131        RemoveSuperfluousReturnNameFixer::class,
132        RemoveSuperfluousVarNameFixer::class,
133        SingleLineInlineVarDocBlockFixer::class,
134        SwitchedTypeAndNameFixer::class,
135    ];
136
137    private const string LEGACY_PHPDOC_TAG_FIXER = 'Symplify\\CodingStandard\\Fixer\\Commenting\\ParamReturnAndVarTagMalformsFixer';
138
139    /**
140     * Creates the default ECS configuration.
141     *
142     * @param callable|null $customize optional callback to customize the configuration builder
143     *
144     * @return ECSConfigBuilder the configured ECS configuration builder
145     */
146    public static function configure(?callable $customize = null): ECSConfigBuilder
147    {
148        $workingDirectory = getcwd();
149        $config = new ECSConfigBuilder();
150
151        self::applyDefaultPathsAndSkips($config, $workingDirectory);
152        self::applyDefaultRulesAndSets($config);
153
154        if (null !== $customize) {
155            $customize($config);
156        }
157
158        return $config;
159    }
160
161    /**
162     * Applies the default repository paths and skipped rules to an ECS builder.
163     *
164     * @param ECSConfigBuilder $config
165     * @param string $workingDirectory
166     */
167    public static function applyDefaultPathsAndSkips(
168        ECSConfigBuilder $config,
169        string $workingDirectory
170    ): ECSConfigBuilder {
171        $paths = WorkingProjectPathResolver::getToolingSourcePaths($workingDirectory);
172        $skipPaths = WorkingProjectPathResolver::getToolingExcludedDirectories();
173
174        return $config
175            ->withPaths($paths)
176            ->withSkip([...$skipPaths, ...self::DEFAULT_SKIPPED_RULES]);
177    }
178
179    /**
180     * Applies the default ECS sets, root files, and configured rules to an ECS builder.
181     *
182     * @param ECSConfigBuilder $config
183     */
184    public static function applyDefaultRulesAndSets(ECSConfigBuilder $config): ECSConfigBuilder
185    {
186        $config
187            ->withRootFiles()
188            ->withPreparedSets(
189                psr12: self::DEFAULT_PREPARED_SETS['psr12'],
190                common: self::DEFAULT_PREPARED_SETS['common'],
191                cleanCode: self::DEFAULT_PREPARED_SETS['cleanCode'],
192            );
193
194        $config->withSets([__DIR__ . '/../../resources/ecs/php-cs-fixer.php']);
195
196        foreach (self::DEFAULT_CONFIGURED_RULES as $rule => $configuration) {
197            $config->withConfiguredRule($rule, $configuration);
198        }
199
200        return $config;
201    }
202
203    /**
204     * Registers PHP-CS-Fixer presets and the legacy Symplify set without deprecated ECS APIs.
205     *
206     * @param ECSConfigInterface $config
207     */
208    public static function applyPhpCsFixerSets(ECSConfigInterface $config): void
209    {
210        $ruleSet = new RuleSet([
211            '@Symfony' => self::DEFAULT_PHP_CS_FIXER_SETS['symfony'],
212            '@Symfony:risky' => self::DEFAULT_PHP_CS_FIXER_SETS['symfonyRisky'],
213            '@auto' => self::DEFAULT_PHP_CS_FIXER_SETS['auto'],
214            '@auto:risky' => self::DEFAULT_PHP_CS_FIXER_SETS['autoRisky'],
215        ]);
216        $fixerFactory = new FixerFactory();
217        $fixerFactory->registerBuiltInFixers();
218        $fixerFactory->useRuleSet($ruleSet);
219        foreach ($fixerFactory->getFixers() as $fixer) {
220            $configuration = $ruleSet->getRuleConfiguration($fixer->getName());
221
222            if (null === $configuration) {
223                $config->rule($fixer::class);
224            } else {
225                $config->ruleWithConfiguration($fixer::class, $configuration);
226            }
227        }
228
229        if (self::DEFAULT_PREPARED_SETS['symplify']) {
230            $config->rules([
231                RemovePHPStormAnnotationFixer::class,
232                ...self::phpdocTagFixers($config),
233                RemoveUselessDefaultCommentFixer::class,
234                RemoveMethodNameDuplicateDescriptionFixer::class,
235                RemovePropertyVariableNameDescriptionFixer::class,
236                ArrayListItemNewlineFixer::class,
237                ArrayOpenerAndCloserNewlineFixer::class,
238                StandaloneLinePromotedPropertyFixer::class,
239                MethodChainingNewlineFixer::class,
240                SpaceAfterCommaHereNowDocFixer::class,
241                BlankLineAfterStrictTypesFixer::class,
242                LineLengthFixer::class,
243            ]);
244            $config->ruleWithConfiguration(GeneralPhpdocAnnotationRemoveFixer::class, [
245                'annotations' => ['throws', 'author', 'package', 'group', 'covers', 'category'],
246            ]);
247        }
248    }
249
250    /**
251     * @return list<class-string>
252     */
253    private static function phpdocTagFixers(ECSConfigInterface $config): array
254    {
255        foreach (self::PHPDOC_TAG_FIXERS as $fixer) {
256            if (! class_exists($fixer)) {
257                // Older supported ECS releases bundle the original complete fixer.
258                return [self::LEGACY_PHPDOC_TAG_FIXER];
259            }
260        }
261
262        // Recent ECS versions already register the successors in the clean-code set.
263        if (method_exists($config, 'getCheckerClasses')) {
264            return array_values(array_diff(self::PHPDOC_TAG_FIXERS, $config->getCheckerClasses()));
265        }
266
267        return self::PHPDOC_TAG_FIXERS;
268    }
269}