You can nudge your life in a new direction every day.

Setting Up Visual Studio Code for Drupal Coding Standard

Submitted by admin on Sun, 10/25/2020 - 19:26

It took me most of the day to get this set up like I want it. It still doesn't work exactly as I like or expect.

After exploring most of extensions I landed on two Visual Studio Code extensions

This is my composer.json

composer global require squizlabs/php_codesniffer
composer global require drupal/coder
    "require": {
        "squizlabs/php_codesniffer": "^3.5",
        "drupal/coder": "^8.3"

Here are the relevant parts of my Visual Studio Code settings.json

This first part is setting up default behavior.

 "php.validate.executablePath": "C:/Users/butle/src/php/php.exe",
    "files.associations": {
        "*.inc": "php",
        "*.module": "php"
    "[php]": {
        "editor.detectIndentation": false,
        "editor.insertSpaces": true,
        "editor.tabSize": 2,
        "editor.defaultFormatter": "bmewburn.vscode-intelephense-client",

Important things to note here:

  • the file association don't work with PHP Sniffer -- you will see how I handle linting below.
  • "editor.detectIndentation": false will keep Visual Studio Code from trying to auto detect style and spacing.
  • "editor.tabSize": 2 is set to conform tabs to Drupal coding standard

These next parts are configurations for the extensions

"phpSniffer.standard": "C:path/to/Composer/vendor/drupal/coder/coder_sniffer/Drupal/ruleset.xml",
    "phpSniffer.autoDetect": true,
    "": "onType",
    "intelephense.format.braces": "k&r",

The two that require a little explanation are:

  • phpSniffer.standard points to the absolute path of the Drupal coding standards ruleset
  • intelephense.format.braces tells the PHP Intelephense formatter to keep the opening bracket inline with the function header

The PHP Intelephense formatter will get you pretty close and PHP Sniffer will tell you where you code doesn't meet Drupal coding standards.

However I ran into two problems:

  • PHP Sniffer would not recognize the .module file extension at PHP 
  • I was unable to get any formatter to attempt to correct any Drupal coding standards errors.

I handled that from the command line by running the following commands.

phpcs --standard=path/to/ruleset.xml --extensions=php,module path/to/file/example.module

phpcbf --standard=path/to/ruleset.xml --extensions=php,module path/to/file/example.module

I hope this helps!