Posted on in #development #laravel

Us developers can be quite picky and have certain ways of working and writing code, spaces vs tabs for example! But if you're working in a team or across multiple projects it's always good to have consistency. If code is formatted all the same it's much easier to get to the gritty details of how & what the code is doing.

Getting a tool to do this automatically so you don't have to think about it is where PHP-CS-Fixer comes in. Installation is easy:

composer global require friendsofphp/php-cs-fixer

Running it for PSR-2 is simple and you can use the --dry-run flag to output any fixes before it runs and finally fixing all violations with:

php-cs-fixer fix --rules=@PSR2 --verbose --diff app

There are quite a lot of different rules you can apply so instead of appending them all to the command you can create a per project .php_cs.dist file which will then be used when running php-cs-fixer fix, an example here uses PSR-2 and the array_syntax rule which has an option:

<?php

$finder = PhpCsFixer\Finder::create()
    ->in(__DIR__.DIRECTORY_SEPARATOR.'app')
;

return PhpCsFixer\Config::create()
    ->setRules([
        '@PSR2' => true,
    ])
    ->setFinder($finder)
;

Bitbucket Pipelines

Running the fixer automatically in a pipeline is quite straight forward, first require the package in your app as a dev dependency:

composer require friendsofphp/php-cs-fixer --dev

Then add the fix command to your pipeline scripts, note it's using the --stop-onviolation & --using-cache=no flags. A complete bitbucket-pipelines.yml file I've got on a project looks like this to check for fixes and finally run the test suite.

image: php:7.1.29

pipelines:
  default:
    - step:
        caches:
          - composer
        artifacts:
          - storage/logs/*.log
        script:
          #- apt-get update && apt-get install -y unzip
          # Installing first the libraries necessary to configure and install gd
          - apt-get update && apt-get install -y unzip libfreetype6-dev libjpeg62-turbo-dev libpng-dev
          # Now we can configure and install the extension
          - docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/
          - docker-php-ext-install -j$(nproc) gd
          - curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
          - php -r "file_exists('.env') || copy('.env.example', '.env');"
          - composer install
          - php artisan key:generate
          - vendor/bin/php-cs-fixer fix -v --dry-run --stop-on-violation --using-cache=no
          - vendor/bin/phpunit

Useful links