PHP CS Fixer

PHP CS Fixer using Github action


If you would like to have consistent code styling in your project(s), Then you absolutely must read this article.

If you’re working in a team of more than 2 people, You must have had times when you find your colleague’s coding style mildly infuriating. So you sit down & fix all those empty lines & commas to look a bit ahem aesthetical.

For the folks who code in php, Checkout the utility called PHP-CS-FIXER. It fixes code style in your project by the press of a single command.

There are list of rules you can apply to the style fixer utility, You can checkout the full list here: Php cs fixer configurations

The PHP Coding Standards Fixer (PHP CS Fixer) tool fixes your code to follow standards; whether you want to follow PHP coding standards as defined in the PSR-1, PSR-2, etc., or other community driven ones like the Symfony one. You can also define your (team’s) style through configuration.

You can run this tool in-order to fix styling issues locally.

But we are interested in automating this process on each commit with the use of Github Actions.

  1. Firstly you will need a PHP-CS-FIXER config file which will instruct the runner about all the code stlying rules you want to follow.

This will provide most commonly used config for a Laravel Project.

  1. Copy & paste the content of config file from previous step into .php_cs file.

  2. In the root of your project, Create a folder .github. Inside that folder, create another folder workflows. And create style.yml file. (.github/workflows/style.yml)

Paste this workflow yml in the file you just created:


name: Check & fix styling

on: [push]

jobs:
  style:
    runs-on: ubuntu-latest

    steps:
      -   name: Checkout code
          uses: actions/checkout@v2

      -   name: Fix style
          uses: docker://oskarstark/php-cs-fixer-ga
          with:
            args: --config=.php_cs --allow-risky=yes

      -   name: Extract branch name
          shell: bash
          run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})"
          id: extract_branch

      -   name: Commit changes
          uses: stefanzweifel/git-auto-commit-action@v2.3.0
          with:
            commit_message: Fix styling
            branch: ${{ steps.extract_branch.outputs.branch }}
          env:
            GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  1. Now you just have to push a new commit to github & you’ll see a new runner working for you. And within a few minutes you will see an auto commit that fixes inconsistent coding styles.

Cheers :)