← All posts

Testing

PHP_CodeSniffer: Enforce Drupal Coding Standards Automatically

PHP_CodeSniffer checks your PHP against coding standards like Drupal's - and phpcbf auto-fixes most of what it flags.

P Testing

Coding standards are the kind of thing everyone agrees on and no one wants to enforce by hand. Indentation, doc comment format, array syntax, naming - reviewing all of it manually is slow and inconsistent. PHP_CodeSniffer makes it mechanical: phpcs checks your code against a defined standard and reports every violation with its exact line, and its companion phpcbf automatically fixes the large share of them that can be fixed by machine.

Lint Against the Drupal Standard

With the Drupal Coder package installed, PHPCS knows the Drupal and DrupalPractice standards, so it checks your custom code against the exact conventions Drupal expects:

# Check custom code against Drupal standards vendor/bin/phpcs --standard=Drupal,DrupalPractice web/modules/custom # Auto-fix everything that can be fixed vendor/bin/phpcbf --standard=Drupal web/modules/custom

phpcbf Fixes Most of It

The auto-fixer is what makes this painless. Rather than hand-correcting whitespace and formatting one report at a time, you run phpcbf, it rewrites the fixable violations in place, and you're left reviewing only the handful that need a human decision.

Wire It Into Your Workflow

PHPCS belongs in a pre-commit hook and in review, so style is enforced automatically instead of argued about. You can tune which sniffs apply with a phpcs.xml in the project root.

Rough Edges and Limitations

  • Style, not bugs. It checks conventions, not correctness - pair it with static analysis and tests.
  • Not everything auto-fixes. phpcbf handles formatting; structural findings still need you.
  • Standards need the right package. The Drupal standards come from the Coder package; without it, phpcs only knows the generic ones.
  • Custom rulesets take tuning. Silencing noise on a legacy codebase means curating your phpcs.xml.

For any Drupal custom code, PHPCS plus the Drupal standard is the baseline - consistent style, enforced automatically, with most of the fixes applied for you.

Internal link suggestion: link "static analysis" to the PHPStan post to pair style enforcement with bug-finding.