? 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
![](https://web.archive.org./web/20210817120352im_/https://i2.wp.com/dominikschilling.de/wp-content/uploads/2020/04/github-check-annotations.png?resize=300%2C149&ssl=1)
- A workflow file with GitHub Actions to set up PHP with Composer and to run PHP_CodeSniffer.
- To prevent the branch from being merged we can make use of protected branches with the
phpcs
check as a required status check. - Coding standard violations will be displayed via check annotations in Checks via cs2pr.
![](https://web.archive.org./web/20210817120352im_/https://i0.wp.com/dominikschilling.de/wp-content/uploads/2020/04/github-action-job.png?resize=660%2C359&ssl=1)
? Workflow file
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