Skip to content

Instantly share code, notes, and snippets.

@back-2-95
Last active August 30, 2023 05:37
Show Gist options
  • Save back-2-95/7ee7cc712562a3d5396555f2c3aaf6f7 to your computer and use it in GitHub Desktop.
Save back-2-95/7ee7cc712562a3d5396555f2c3aaf6f7 to your computer and use it in GitHub Desktop.
How to get PHP CodeSniffer for Drupal working in PhpStorm

Step 1

Create file called phpcs.xml.dist to your repository root with following content:

<?xml version="1.0"?>
<ruleset name="Drupal Standard">
  <description>A Drupal coding standard</description>
  <config name="drupal_core_version" value="8"/>
  <rule ref="./vendor/drupal/coder/coder_sniffer/Drupal"/>
  <rule ref="./vendor/drupal/coder/coder_sniffer/DrupalPractice"/>
  <arg name="extensions" value="php,module,inc,install,js,theme,twig,yml"/>
  <file>./drush</file>
  <file>./public/modules/custom</file>
  <file>./public/themes/custom</file>
  <!--<file>./tests</file>-->
  <exclude-pattern>*/contrib/*</exclude-pattern>
  <exclude-pattern>*/dist/*</exclude-pattern>
  <exclude-pattern>*/node_modules/*</exclude-pattern>
  <exclude-pattern>*/vendor/*</exclude-pattern>
</ruleset>

Step 2

Require package squizlabs/php_codesniffer with Composer. PhpStorm uses this to autodetect that PHP_CodeSniffer is used.

composer require --dev squizlabs/php_codesniffer

Note! Package already exists as it's required by drupal/core-dev-pinned and multiple others. It's just needed on the root level of composer.lock to PhpStorm to autodetect it.

Step 3

Add file extensions to check in Settings >> PHP >> Quality Tools >> PHP_CodeSniffer

This is needed as PhpStorm does not autoconfigure these from phpcs.xml.dist.

image

Step 4 (if needed)

Sometimes it is needed to re-index site to get it working.

  • Close PhpStorm
  • Clear settings for the project: rm -rf .idea
  • Open PhpStorm and project again
<?php
/**
* @file
* Configure PhpStorm plugin for PHP Code Sniffer.
*/
$xmlPHPCodeSniffer = 'phpcs.xml.dist';
$xmlFilePhpStorm = '.idea/php.xml';
if (file_exists($xmlPHPCodeSniffer) && file_exists($xmlFilePhpStorm)) {
$xmlPHPCodeSniffer = simplexml_load_file($xmlPHPCodeSniffer);
$xpath = '//ruleset/arg[@name="extensions"]';
$node = $xmlPHPCodeSniffer->xpath($xpath);
$extensions = $node[0]['value'];
if ($extensions) {
$xmlPhpStorm = simplexml_load_file($xmlFilePhpStorm);
$xpath = '//project/component[@name="PHPCodeSnifferOptionsConfiguration"]/option[@name="extensions"]';
$node = $xmlPhpStorm->xpath($xpath);
if (isset($node[0]['value'])) {
$node[0]['value'] = $extensions;
$xmlPhpStorm->asXML($xmlFilePhpStorm);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment