Skip to main content

PHPCS - PHP Code Sniffer

https://github.com/PHPCSStandards/PHP_CodeSniffer/

PHP_CodeSniffer is a set of two PHP scripts; the main phpcs script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second phpcbf script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent.

Vortex comes with pre-configured PHPCS ruleset for Drupal projects.

Usage

Check for violations

ahoy lint-be

Fix violations

# Fix all back-end lint issues (Rector, then PHPCBF).
ahoy lint-be-fix

Configuration

See configuration reference.

All global configuration takes place in the phpcs.xml file.

By default, PHPCS will check against the following rules:

  • Drupal
  • DrupalPractice
  • Generic.PHP.RequireStrictTypes
  • PHPCompatibility
  • DrevOps
  • SlevomatCodingStandard.TypeHints.DNFTypeHintFormat

Targets include custom modules and themes, settings, tests and scripts.

Adding or removing targets:

<file>path/to/dir_or_file</file>

The PHPCompatibility checks run against the platform version specified in the composer.json key config.platform.php:

<config name="testVersion" value="8.4"/>

Ignoring

Ignoring rules globally takes place in the phpcs.xml file:

<!-- Comment about why this rule is excluded. -->
<rule ref="DrupalPractice.General.ClassName.ClassPrefix">
<exclude-pattern>*\/dir\/another\/*\.php</exclude-pattern>
<exclude-pattern>*\/dir\/another\/*\.inc</exclude-pattern>
</rule>

To ignore all PHPCS rules within a file, place in the file header:

// phpcs:ignoreFile

To ignore a specific rule within a file, place in the file header:

// phpcs:disable <rule_name>

To ignore rule for the code block:

// phpcs:disable <rule_name>
$a = 1;
// phpcs:enable <rule_name>

To ignore only the next line:

// phpcs:ignore
$a = 1;

Continuous integration

PHPCS runs in the lint job of the continuous integration pipeline and fails the build on violations.

Ignoring failures

Set the VORTEX_CI_PHPCS_IGNORE_FAILURE environment variable to 1. The tool still runs and reports violations.

➡️ See Continuous integration > Ignore tool failures