Optimizing Code Quality: A Deep Dive into Easy Coding Standard.

Jan 21, 2024General
featured-image

One of the aspects i truly enjoy when coding in PHP is maintaining a structured approach, adhering to a standardized format that everyone can comprehend. For this purpose, I follow PSR-12 and the new PERCS20 standard. While i am familiar with some rules, practicality often doesn't demand knowledge of every single one. I'll guide you on utilizing my shared ESC action, which automates the standardization of your code effortlessly.


Steps to Implement Easy Coding Standard:

  •  Install with Composer
composer require symplify/easy-coding-standard --dev
  • Add config in root directory name esc.php.
<?php
declare(strict_types=1);
use PhpCsFixer\Fixer\ClassNotation\ClassDefinitionFixer;
use PhpCsFixer\Fixer\ClassNotation\OrderedClassElementsFixer;
use PhpCsFixer\Fixer\ClassNotation\OrderedTraitsFixer;
use PhpCsFixer\Fixer\Import\NoUnusedImportsFixer;
use Symplify\EasyCodingStandard\Config\ECSConfig; return ECSConfig::configure()
->withConfiguredRule(
ClassDefinitionFixer::class,
[
'space_before_parenthesis' => true,
],
)
->withFileExtensions(['php'])
->withPaths(
[
__DIR__ . '/src',
__DIR__ . '/tests',
],
)
->withPhpCsFixerSets(perCS20: true)
->withPreparedSets(
arrays: true,
cleanCode: true,
comments:true,
docblocks: true,
namespaces: true,
psr12: true,
strict: true
)
->withRules(
[
NoUnusedImportsFixer::class,
OrderedClassElementsFixer::class,
OrderedTraitsFixer::class,
]
);
  • Now we check from the cli console, with the following command to see the errors in our code.
vendor/bin/ecs
  • In the console output, if we have errors, we can correct them automatically with the following command.
vendor/bin/ecs --fix
  • Now if we want to automate our ci, we can add it in github actions, simply by adding the ecs.yml file to the ./github/workflows folder.
on:
  pull_request:
    paths-ignore:
      - 'docs/**'
      - 'README.md'
      - 'CHANGELOG.md'
      - '.gitignore'
      - '.gitattributes'
      - 'infection.json.dist'
      - 'phpunit.xml.dist'
  push:
    branches: ['main']
    paths-ignore:
      - 'docs/**'
      - 'README.md'
      - 'CHANGELOG.md'
      - '.gitignore'
      - '.gitattributes'
      - 'infection.json.dist'
      - 'phpunit.xml.dist'
name: ecs
jobs:
  easy-coding-standard:
    uses: php-forge/actions/.github/workflows/ecs.yml@main
    secrets:
      AUTH_TOKEN: ${{ secrets.AUTH_TOKEN }}
    with:
      os: >-
        ['ubuntu-latest']
      php: >-
        ['8.1']


Happy coding!