The Easiest way to start using PHP CS Fixer and PHP_CodeSniffer with 0-knowledge

Overview

The Easiest Way to Use Any Coding Standard

Downloads total

ECS-Run

Features

  • Blazing fast Parallel run
  • Use PHP_CodeSniffer || PHP-CS-Fixer - anything you like
  • 2nd run under few seconds with un-changed file cache
  • Skipping files for specific checkers
  • Prepared sets - PSR12, Symfony, arrays, use statements, spaces and more... - see SetList class for all
  • Prefixed version by default to allow install without conflicts

Are you already using another tool?

Install

composer require symplify/easy-coding-standard --dev

Usage

1. Create Configuration and Setup Checkers

  • Create an ecs.php in your root directory
  • Add Sniffs
  • ...or Fixers you'd love to use
// ecs.php
use PhpCsFixer\Fixer\ArrayNotation\ArraySyntaxFixer;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\EasyCodingStandard\ValueObject\Set\SetList;

return static function (ContainerConfigurator $containerConfigurator): void {
    // A. full sets
    $containerConfigurator->import(SetList::PSR_12);

    // B. standalone rule
    $services = $containerConfigurator->services();
    $services->set(ArraySyntaxFixer::class)
        ->call('configure', [[
            'syntax' => 'short',
        ]]);
};

Full Sets before Standalone Rules

It is highly recommended to imports sets (A) first, then add standalone rules (B).

The reason for this is that some settings are configured in the full sets too, and will therefore overwrite your standalone rules, if not configured first.

2. Run in CLI

# dry
vendor/bin/ecs check src

# fix
vendor/bin/ecs check src --fix

Features

How to load own config?

vendor/bin/ecs check src --config another-config.php

Configuration

Configuration can be extended with many options. Here is list of them with example values and little description what are they for:

set(Option::FILE_EXTENSIONS, ['php', 'phpt']); // configure cache paths & namespace - useful for Gitlab CI caching, where getcwd() produces always different path // [default: sys_get_temp_dir() . '/_changed_files_detector_tests'] $parameters->set(Option::CACHE_DIRECTORY, '.ecs_cache'); // [default: \Nette\Utils\Strings::webalize(getcwd())'] $parameters->set(Option::CACHE_NAMESPACE, 'my_project_namespace'); // indent and tabs/spaces // [default: spaces] $parameters->set(Option::INDENTATION, 'tab'); // [default: PHP_EOL]; other options: "\n" $parameters->set(Option::LINE_ENDING, "\r\n"); };">
use PhpCsFixer\Fixer\ArrayNotation\ArraySyntaxFixer;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\EasyCodingStandard\ValueObject\Option;

return static function (ContainerConfigurator $containerConfigurator): void {
    $parameters = $containerConfigurator->parameters();

    // alternative to CLI arguments, easier to maintain and extend
    $parameters->set(Option::PATHS, [__DIR__ . '/src', __DIR__ . '/tests']);

    // run single rule only on specific path
    $parameters->set(Option::ONLY, [
        ArraySyntaxFixer::class => [__DIR__ . '/src/NewCode'],
    ]);

    $parameters->set(Option::SKIP, [
        // skip paths with legacy code
        __DIR__ . '/packages/*/src/Legacy',

        ArraySyntaxFixer::class => [
            // path to file (you can copy this from error report)
            __DIR__ . '/packages/EasyCodingStandard/packages/SniffRunner/src/File/File.php',

            // or multiple files by path to match against "fnmatch()"
            __DIR__ . '/packages/*/src/Command',
        ],

        // skip rule completely
        ArraySyntaxFixer::class,

        // just single one part of the rule?
        ArraySyntaxFixer::class . '.SomeSingleOption',

        // ignore specific error message
        'Cognitive complexity for method "addAction" is 13 but has to be less than or equal to 8.',
    ]);

    // scan other file extendsions; [default: [php]]
    $parameters->set(Option::FILE_EXTENSIONS, ['php', 'phpt']);

    // configure cache paths & namespace - useful for Gitlab CI caching, where getcwd() produces always different path
    // [default: sys_get_temp_dir() . '/_changed_files_detector_tests']
    $parameters->set(Option::CACHE_DIRECTORY, '.ecs_cache');

    // [default: \Nette\Utils\Strings::webalize(getcwd())']
    $parameters->set(Option::CACHE_NAMESPACE, 'my_project_namespace');

    // indent and tabs/spaces
    // [default: spaces]
    $parameters->set(Option::INDENTATION, 'tab');

    // [default: PHP_EOL]; other options: "\n"
    $parameters->set(Option::LINE_ENDING, "\r\n");
};

Parallel Run

Do you have multi-core CPUs? ECS can run in X parallel threads, where X is number of your threads. E.g. with laptop with AMD Ryzen 4750U it is 16.

That means 1600 % faster run with same amount of analysed files. Did you code base took 16 minutes to fix? Now it's 1 minute.

How to enable it?

use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\EasyCodingStandard\ValueObject\Option;

return static function (ContainerConfigurator $containerConfigurator): void {
    $parameters = $containerConfigurator->parameters();

    $parameters->set(Option::PARALLEL, true);
};

Coding Standards in Markdown

ECS-Run


How to correct PHP snippets in Markdown files?

vendor/bin/ecs check-markdown README.md
vendor/bin/ecs check-markdown README.md docs/rules.md

# to fix them, add --fix
vendor/bin/ecs check-markdown README.md docs/rules.md --fix

Do you have already paths defined in ecs.php config? Drop them from CLI and let ECS use those:

vendor/bin/ecs check-markdown --fix

FAQ

How can I see all loaded checkers?

vendor/bin/ecs show
vendor/bin/ecs show --config ...

How do I clear cache?

vendor/bin/ecs check src --clear-cache

Report Issues

In case you are experiencing a bug or want to request a new feature head over to the Symplify monorepo issue tracker

Contribute

The sources of this package are contained in the Symplify monorepo. We welcome contributions for this package on symplify/symplify.

Acknowledgment

The parallel run is package is heavily inspired by https://github.com/phpstan/phpstan-src by Ondřej Mirtes. Thank you.

Comments
  • Feature/drupal

    Feature/drupal

    This adds the Drupal coding standard to the tool.

    I can imagine an alternative approach to this would be to allow the addSearchPath call to be a parameter that is passed or set somehow. I did not explore this scenario.

    For my own future reference, it took me looking at src//DependencyInjection/CompilerPass/FixerWhitespaceConfigCompilerPass.php to understand why the sniff wasn't getting loaded. Also phpcs -e --standard=Drupal can be used to get a list of sniffs.

    opened by josephdpurcell 2
  • Allow PrettyVersion 2

    Allow PrettyVersion 2

    This simple bump allows for the 2.0 version of this lib, which leverages Composer 2 APIs and drops any sub dependency.

    There are basically no BC; for more details, see the the changelog.

    opened by Jean85 1
  • switch Option to notdeprecated one in imports

    switch Option to notdeprecated one in imports

    The file ecs.php.dist encourages developers to use an outdated Option class:

    • Symplify\EasyCodingStandard\Configuration\Option is flagged as @deprecated
    • it should be replaces with Symplify\EasyCodingStandard\ValueObject\Option
    opened by krzysztofrewak 1
  • Remove SmartFileInfo and use string paths instead

    Remove SmartFileInfo and use string paths instead

    Move away from files infos, as bloated value objects without any value. They only slowdown the process and passing data between parallel processes. Now the ECS should be faster and easier to use with tests :slightly_smiling_face:

    Mirror to https://github.com/rectorphp/rector-src/pull/2878

    opened by TomasVotruba 0
  • [easy-coding-standard] Call to undefined function ECSPrefix202210\trigger_deprecation()

    [easy-coding-standard] Call to undefined function ECSPrefix202210\trigger_deprecation()

    In version 11.1.11 and hight it fails with error Call to undefined function ECSPrefix202210\trigger_deprecation().

    It fails at vendor/symplify/easy-coding-standard/vendor/symfony/dependency-injection/ContainerBuilder.php:896.

    opened by alexndlm 10
  • Cache invalidation on configuration change

    Cache invalidation on configuration change

    On some configuration changes the cache is not properly invalidated.

    For example this fixer:

        $ecsConfig->ruleWithConfiguration(FinalInternalClassFixer::class, [
            'annotation_exclude' => ['@not-fix'],
            'consider_absent_docblock_as_internal_class' => \true
        ]);
    

    When running it with the configuration array empty, it marks a lot of files as shiny. But then, if I change it to this:

        $ecsConfig->ruleWithConfiguration(FinalInternalClassFixer::class, [
            'annotation_exclude' => ['@not-fix'],
            'annotation_include' => [],
            'consider_absent_docblock_as_internal_class' => \true
        ]);
    

    It becomes applicable to a lot more files (the default for annotation_include is to require an @internal entry). But rerunning ECS doesn't work discover those.

    If I run it with ecs --clear-cache it does work correctly. Note that going the other way is not an issue since faulty files are always (re)checked.

    A simple solution would be to take a "hash" of the ECSConfig instance and always fully invalidate the cache when it has changed. Since I'm not familiar with Symfony's DI configurator stuff I don't know if this is supported by default. Of course an easy naive implementation is to just log all calls to the ECSConfig to create a hash:

    private string $liveHash = '';
    public function ruleWithConfiguration(string $checkerClass, array $configuration) : void
    {
        $this->liveHash = md5($this->liveHash . $checkClass . json_encode($configuration));
    }
    
    

    This would then need to be done for every function on ECS config. Note that even doing this partially improves the situation, since currently all changes are ignored.

    opened by SamMousa 0
  • [ECS] ECS fails when working without cache

    [ECS] ECS fails when working without cache

    Hello,

    when using ECS without cache (ie with --clear-cache or after cache dir was manually deleted or invalidated after fixes) the process ends silently on error without any error message.

    when running without clearing a cache, the process ends up as expected with green message about shiny code.

    It's more apparent when running ecs as a composer script or as a part of series of scripts - because composer stops on error

    I've created basic repository to reproduce the error: https://github.com/noximo/ecs-test

    Turning off paralelization solves the issue but leads to significant slowdowns.

    Passing -vvv or --debug doesn't provide any additional info, just a list of fixers.

    opened by noximo 4
Releases(10.2.4)
  • 10.2.4(Jun 4, 2022)

    Make use of native ECSConfig in ecs.php

    Running ECS on Symfony project can create conflict with native ContainerConfigurator. To avoid that, we introduce a new config, that is fully scoped and isolated within ECS.

    Another big advantage is new configuration methods with validation and autocomplete right in your ide :+1:


    Read more in https://tomasvotruba.com/blog/new-in-ecs-simpler-config/

    Before :skull:

    use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
    use Symplify\EasyCodingStandard\ValueObject\Option;
    
    // ups, possible conflict with ContainerConfigurator
    return static function (ContainerConfigurator $containerConfigurator): void {
        $parameters = $containerConfigurator->parameters();
    
        // too verbose params, constants and possible typo in param value
        $parameters->set(Option::PATHS, [[ // ups, "[[" typo
            __DIR__ . '/src/',
        ]]);
    
        $services = $containerConfigurator->services();
        $services->set(ArraySyntaxFixer::class);
    };
    

    Now :tada:

    use Symplify\EasyCodingStandard\Config\ECSConfig;
    use Symplify\EasyCodingStandard\ValueObject\Set\SetList;
    
    return static function (ECSConfig $ecsConfig): void {
        $ecsConfig->paths([
            __DIR__ . '/src',
        ]);
    
        $ecsConfig->rule(ArraySyntaxFixer::class);
    
        $ecsConfig->sets([SetList::PSR_12]);
    };
    
    Source code(tar.gz)
    Source code(zip)
  • 9.4.67(Sep 29, 2021)

    ECS gets 100 % faster per 1 CPU thread :rocket:

    Do you have multi-core CPUs? ECS can run in X parallel threads, where X is number of your threads. E.g. with laptop with AMD Ryzen 4750U it is 16.

    That means 1600 % faster run with same amount of analysed files. Did you code base took 16 minutes to fix? Now it's 1 minute.

    This feature is:

    • experimental - please test and report any issue at https://github.com/symplify/symplify/issues/new :bug:
    • should work on Windows too

    Do you Want to Safe Time? :timer_clock:

    Try it:

    // ecs.php
    use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
    use Symplify\EasyCodingStandard\ValueObject\Option;
    
    return static function (ContainerConfigurator $containerConfigurator): void {
        $parameters = $containerConfigurator->parameters();
    
        $parameters->set(Option::PARALLEL, true);
    };
    

    And that's it :wink:


    Aknowledgements

    The parallel run is heavily based on @phpstan parallel run - thanks to Ondřej Mirtes for inspiration :pray:

    Source code(tar.gz)
    Source code(zip)
  • v9.3.3(May 17, 2021)

    Dowgraded and Scoped version by Default

    Since 9.3.3, the package is downgraded to PHP 7.1 and scoped. The former package https://github.com/symplify/easy-coding-standard-prefixed is deprecated and replaced by symplify/easy-coding-standard should be used instead.

    Read more in standalone post https://tomasvotruba.com/blog/introducing-ecs-prefixed-and-downgraded-to-php-71

    Source code(tar.gz)
    Source code(zip)
Owner
Easy Coding Standard, Static Site Generator, Package Builder utils on PHP 8.0 and Symfony 5.4
null
Lightweight PHP wrapper for OVH APIs. That's the easiest way to use OVH.com APIs in your PHP applications.

This PHP package is a lightweight wrapper for OVH APIs. That's the easiest way to use OVH.com APIs in your PHP applications.

OVHcloud 263 Dec 14, 2022
Laravel Blog Package. Easiest way to add a blog to your Laravel website. A package which adds wordpress functionality to your website and is compatible with laravel 8.

Laravel Blog Have you worked with Wordpress? Developers call this package wordpress-like laravel blog. Give our package a Star to support us ⭐ ?? Inst

Binshops 279 Dec 28, 2022
Parsica - PHP Parser Combinators - The easiest way to build robust parsers.

Parsica The easiest way to build robust parsers in PHP. composer require parsica-php/parsica Documentation & API: parsica-php.github.io <?php $parser

null 350 Dec 27, 2022
The easiest way to match data structures like JSON/PlainText/XML against readable patterns. Sandbox:

PHP Matcher Library created for testing all kinds of JSON/XML/TXT/Scalar values against patterns. API: PHPMatcher::match($value = '{"foo": "bar"}', $p

Coduo 774 Dec 31, 2022
The easiest way to get started with event sourcing in Laravel

Event sourcing for Artisans ?? This package aims to be the entry point to get started with event sourcing in Laravel. It can help you with setting up

Spatie 591 Jan 4, 2023
🐋 This project aims to broaden knowledge of system administration by using Docker: virtualizing several Docker images, creating them in a new personal virtual machine.

?? This project aims to broaden knowledge of system administration by using Docker: virtualizing several Docker images, creating them in a new personal virtual machine.

Anton Kliek 1 Jan 26, 2022
Provides a configuration factory and multiple rule sets for friendsofphp/php-cs-fixer.

php-cs-fixer-config Provides a configuration factory and multiple rule sets for friendsofphp/php-cs-fixer. Installation Run $ composer require --dev e

null 37 Jan 2, 2023
php-cs-fixer config for REDAXO

php-cs-fixer config for REDAXO Installation composer require --dev redaxo/php-cs-fixer-config Example .php-cs-fixer.dist.php: <?php $finder = (new P

REDAXO CMS c/o Yakamara Media GmbH & Co. KG 7 Aug 14, 2022
🙈 Code style configuration for `php-cs-fixer` based on PSR-12.

php-code-style Code style configuration for friendsofphp/php-cs-fixer based on PSR-12. Installation Step 1 of 3 Install gomzyakov/php-code-style via c

Alexander Gomzyakov 5 Nov 27, 2022
Laravel Pint is an opinionated PHP code style fixer for minimalists.

Laravel Pint is an opinionated PHP code style fixer for minimalists. Pint is built on top of PHP-CS-Fixer and makes it simple to ensure that your code style stays clean and consistent.

The Laravel Framework 2.2k Jan 5, 2023
php-cs-fixer config for Yakamara projects

php-cs-fixer config for Yakamara projects Installation composer require --dev yakamara/php-cs-fixer-config Example .php-cs-fixer.dist.php: <?php $fi

Yakamara Media GmbH & Co. KG 4 Nov 29, 2022
A repository for showcasing my knowledge of the PHP programming language, and continuing to learn the language.

Learning PHP (programming language) I know very little about PHP. This document will list all my knowledge of the PHP programming language. Basic synt

Sean P. Myrick V19.1.7.2 2 Oct 29, 2022
Cheatsheet for some Php knowledge you will frequently encounter in modern projects.

Cheatsheet for some Php knowledge you will frequently encounter in modern projects.

Arnaud Becher 1.1k Jan 2, 2023
Check modules in app/code and vendor for PHP 8 compatibility status - PHP_CodeSniffer & php-compatibility standard

M2 PHP version compatibility check How To use Requires PHP 7.3+ | PHP 8 This app will run PHP_CodeSniffer with phpcompatibility/php-compatibility on t

William Tran 24 Oct 13, 2022
PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.

PHP_CodeSniffer is a set of two PHP scripts; the main phpcs script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second phpcbf script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent.

Squiz Labs 9.9k Jan 5, 2023
Composer installer for PHP_CodeSniffer coding standards

PHP_CodeSniffer Standards Composer Installer Plugin This composer installer plugin allows for easy installation of PHP_CodeSniffer coding standards (r

Dealerdirect 462 Dec 22, 2022
This composer installer plugin allows for easy installation of PHP_CodeSniffer coding standards

PHP_CodeSniffer Standards Composer Installer Plugin This composer installer plugin allows for easy installation of PHP_CodeSniffer coding standards (r

PHPCSStandards 393 Feb 25, 2022
ExtDN PHP_CodeSniffer rules for Magento 2

ExtDN PHP_CodeSniffer rules for Magento 2 Introduction There are already many PHP CodeSniffer rules out there to aid in Magento 2 development: Magento

ExtDN 81 Dec 16, 2022