This project offers a set of preconfigured rules for PHP Code Sniffer mainly related to new PHP features that are not covered by Drupal coding standards yet.
PHP 8.1+
Install the standard locally through Composer.
composer require --dev chi-teck/drupal-coder-extension
Add DrupalExtended
standard to your project's phpcs.xml
.
<?xml version="1.0"?>
<ruleset name="Drupal Extended"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../vendor/squizlabs/php_codesniffer/phpcs.xsd">
<rule ref="DrupalExtended">
<!-- Sniffs to exclude. -->
</rule>
<!-- Override settings for enabled rules or enable that excluded. -->
<rule ref="SlevomatCodingStandard.Classes.RequireAbstractOrFinal.ClassNeitherAbstractNorFinal">
<exclude-pattern>./src/Exception</exclude-pattern>
</rule>
<rule ref="SlevomatCodingStandard.ControlStructures.EarlyExit"/>
</ruleset>
A complete example of phpcs.xml
:
<?xml version="1.0"?>
<ruleset name="Drupal Extended"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../vendor/squizlabs/php_codesniffer/phpcs.xsd">
<description>PHP Code Sniffer configuration for My Project.</description>
<arg name="colors"/>
<arg name="extensions" value="php,module,inc,install,theme,info,txt,md,yml"/>
<!-- Paths to scan for problems recursively. -->
<file>./web/modules/custom</file>
<file>./web/themes/custom</file>
<file>./tests</file>
<!-- Exclude vendors. -->
<exclude-pattern>./docroot/themes/custom/example/node_modules</exclude-pattern>
<rule ref="DrupalExtended"/>
</ruleset>
Run the phpcs
script to check custom code.
./vendor/bin/phpcs -ps --standard=phpcs.xml
Run the phpcbf
script to automatically correct coding standard violations.
./vendor/bin/phpcbf
You also can put this command into projects composer.json
:
{
…
"scripts": {
"phpcs": "vendor/bin/phpcs -ps"
}
}
Then you can use it like
composer phpcs
GNU General Public License, version 2 or later.