The Ops Community ⚙️

Jason Purdy
Jason Purdy

Posted on

Adding code style check (+ GitHub Action)

Code style dictates how you write code in order to make the code readability consistent throughout your organization. Style is opinionated and there are many different approaches. With my work, we mostly develop in Drupal, which has its own style guide, and there are other PHP style guides for Zend, PSR, etc.

PHP has a code sniffer which can run through your code looking for non-compliant code, given the style you want to comply with. It also comes with a tool (phpcbf) that can automatically fix simple issues.

To get started, you want to add the sniffer to your composer.json require-dev section. If you're also developing with Drupal, you'll want to add the drupal/coder library, which will bring in the Drupal code style guides.

    "require-dev": {
        "drupal/coder": "^8.3.1",
        "squizlabs/php_codesniffer": "^3.4.0"
    }
Enter fullscreen mode Exit fullscreen mode

So that will get the phpcs and phpcbf into the ./vendor/bin directory and you can add a script in your composer.json that will let you run the style check through composer (composer code-sniff). Here's what that section of the json looks like:

    "scripts": {
        "code-sniff": [
            "./vendor/bin/phpcs --standard=Drupal --extensions=php,module,inc,install,test,profile,theme,css,info,txt --ignore=node_modules,bower_components,vendor ./web/modules/custom"
        ],
    }
Enter fullscreen mode Exit fullscreen mode

This will only check the code in ./web/modules/custom, checking our custom code and leaving the external code alone.

I mentioned GitHub Actions before, but you can now add this style check to your Action, by appending a composer install and composer code-sniff to your steps, like so:

jobs:
  build:
    name: Code checkout and checkup
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v1
      - name: Lint check
        uses: overtrue/phplint@7.4
        with:
          path: web
          options: --exclude=core --exclude=libraries --exclude=modules/contrib --exclude=profiles
      - name: Composer install
        run: composer install
      - name: Check coding standards
        run: composer -n code-sniff
Enter fullscreen mode Exit fullscreen mode

Now this action will checkout the code, run a syntax check (excluding external code), do a composer install, and run the code-sniff command. So now with any update to GitHub, it will check for syntax errors and code style issues. The -n argument to the code-sniff command is telling composer to skip any interactions, which are impossible when running through GitHub Actions.

Oldest comments (0)