GitHub Action workflow for running PHP_CodeSniffer on pull requests with check annotations

πŸ€” Idea

For GitHub pull requests, detect any coding standard violations via PHP_CodeSniffer. Errors should prevent the pull request from being merged and displayed to the user.

πŸ“– Implementation

Example of a check annotation
Example of a job output

πŸ— Workflow file

YAML / RAW / github:gist
name: PHP_CodeSniffer

on: pull_request

jobs:
  phpcs:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '7.3'
          coverage: none
          tools: composer, cs2pr

      - name: Get Composer cache directory
        id: composer-cache
        run: echo "::set-output name=dir::$(composer config cache-files-dir)"

      - name: Setup cache
        uses: pat-s/always-upload-cache@v1.1.4
        with:
          path: ${{ steps.composer-cache.outputs.dir }}
          # Use the hash of composer.json as the key for your cache if you do not commit composer.lock. 
          # key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.json') }}
          key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
          restore-keys: ${{ runner.os }}-composer-

      - name: Install dependencies
        run: composer install --prefer-dist --no-suggest --no-progress

      - name: Detect coding standard violations
        run: vendor/bin/phpcs -q --report=checkstyle | cs2pr --graceful-warnings

The workflow file can be saved in the .github/workflows directory of your GitHub repository.

Notes:

  • The workflow is using the pat-s/always-upload-cache action, a fork of actions/cache, which also supports caching if a previous step fails.
  • Your repository should include a configuration file for PHP_CodeSniffer.
  • If the coding standard isn’t one of the defaults it need to be added as (dev) dependency in your project’s composer.json file.
  • Only 10 warning and 10 error annotations per step are currently supported (source). It’s recommended to fix all existing errors before publishing the workflow.
  • To exit with error codes if there are only warnings you can remove the --graceful-warnings flag in the last line.

Questions? Feedback? Let me know in the comments!

Photo by Alexander Sinn on Unsplash

Leave a Reply