Run prettier or php-cs-fixer with GitHub Actions

Stefan Zweifel shares his GitHub Actions Workflows to run prettier and php-cs-fixer on his repos:

Over the past few weeks I’ve added a handful of workflows to my projects.

One workflow is really like, is to run prettier and php-cs-fixer to automatically format my code and commit the fixed files back to the repository.

Here’s the contents of the prettier workflow for example (.github/workflows/format_prettier):

name: Format (prettier)

on:
  pull_request:
    paths:
    - '**.css'
    - '**.js'
    - '**.vue'

jobs:
  prettier:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/[email protected]

    - name: Install
      run: yarn install
      env:
        CI: true

    - name: Run prettier
      run: yarn run prettier --write 'src/**/*.{css,js,vue}'

    - uses: stefanzweifel/git-auto-co[email protected]
      with:
        commit_message: Apply prettier changes
        branch: ${{ github.head_ref }}
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Upon each PR the workflow spins up an ubuntu machine which:

  1. Checks out the code
  2. Installs the dependencies (given that prettier is listed as a dev dependency in package.json)
  3. Runs the linter on certain files, with autofix enabled
  4. Commits all changes made by the linter

The php-cs-fixer works in a similar way.

Run prettier or php-cs-fixer with GitHub Actions →

🤩 There’s more cool things you can do with GitHub Actions. Automatically compressing (image) assets for example is a really neat workflow. You can even use GitHub Actions to schedule deploys of your site.

🤔 Looking to set up prettier and/or php-cs-fixer? Look no further.

Freek on Twitter

Tools to automatically format PHP, JavaScript and CSS files

Good writeup by Freek on how to get PHP-CS-Fixer and Prettier up and running.

When working on a project with other people, it’s important to pick a coding standard. Agreeing on a coding standard makes the code more readable for all developers that need to touch the project.

It’s easy to make mistakes against those formatting rules and bit cumbersome to fix all small formatting errors. Luckily there are many tools available that can automatically format this code. In this blog post, I’ll show you how to automatically format PHP, JavaScript and CSS files in a Laravel project. Not using Laravel? No problem! Most of this can be applied to any PHP project.

Addtionally I’d recommend to let these linters run in a precommit hook. That way no “faulty” code can be committed, and everyone is forced to adhere to the standards (Although: git commit -n …).

Tools to automatically format PHP, JavaScript and CSS files →

At the end of his post, Freek mentions that you can use Prettier to format your PHP code. The folks at Made With Love have a post on how to use Prettier with PHP.