Skip to content

Add PHP Coding Standards Fixer

ucan-lab edited this page May 18, 2021 · 4 revisions
$ docker compose exec app bash

Work inside the app container.

Install php-cs-fixer

$ composer require --dev bamarni/composer-bin-plugin
$ composer bin tools require friendsofphp/php-cs-fixer

Setting php-cs-fixer

$ touch .php-cs-fixer.dist.php
<?php declare(strict_types=1);

$finder = PhpCsFixer\Finder::create()
    ->in([
        __DIR__ . '/app',
        __DIR__ . '/config',
        __DIR__ . '/database/factories',
        __DIR__ . '/database/seeders',
        __DIR__ . '/routes',
        __DIR__ . '/tests',
    ]);

$config = new PhpCsFixer\Config();

return $config
    ->setRiskyAllowed(true)
    ->setRules([
        '@PhpCsFixer:risky' => true,
        'blank_line_after_opening_tag' => false,
        'linebreak_after_opening_tag' => false,
        'declare_strict_types' => true,
        'phpdoc_types_order' => [
            'null_adjustment' => 'always_last',
            'sort_algorithm' => 'none',
        ],
        'no_superfluous_phpdoc_tags' => false,
        'global_namespace_import' => [
            'import_classes' => true,
            'import_constants' => true,
            'import_functions' => true,
        ],
        'php_unit_test_case_static_method_calls' => [
            'call_type' => 'this'
        ],
        'phpdoc_align' => [
            'align' => 'left',
        ],
        'not_operator_with_successor_space' => true,
    ])
    ->setFinder($finder);

Add .gitignore

/vendor-bin
.php-cs-fixer.cache

Execute php-cs-fixer

# version
$ ./vendor/bin/php-cs-fixer --version
PHP CS Fixer 3.0.0 Constitution by Fabien Potencier and Dariusz Ruminski

# dry run
$ ./vendor/bin/php-cs-fixer fix -v --diff --dry-run

# fix
$ ./vendor/bin/php-cs-fixer fix -v --diff

GitHub Actions

$ mkdir -p .github/workflows
$ touch .github/workflows/integration-php-cs-fixer.yml
name: PHP Coding Standards Fixer

on:
  pull_request:

jobs:
  php-cs-fixer:
    runs-on: ubuntu-latest

    defaults:
      run:
        working-directory: backend

    steps:
      - uses: actions/checkout@v2

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.0'

      - name: Prepare
        run: |
          wget https://github.com/FriendsOfPHP/PHP-CS-Fixer/releases/download/v3.0.0/php-cs-fixer.phar -O php-cs-fixer
          chmod a+x php-cs-fixer

      - name: OS Version
        run: cat /etc/os-release

      - name: PHP Version
        run: php -v

      - name: PHP CS Fixer Version
        run: php php-cs-fixer --version

      - name: PHP CS Fixer Run
        run: php php-cs-fixer fix --diff -vvv --dry-run