pfrenssen / drupal-sniffs
PHP_CodeSniffer sniffs that align Drupal projects with the conventions of Drupal core.
Package info
github.com/pfrenssen/drupal-sniffs
Type:phpcodesniffer-standard
pkg:composer/pfrenssen/drupal-sniffs
Requires
- php: >=8.3
- ext-mbstring: *
- dealerdirect/phpcodesniffer-composer-installer: ^1.0
- slevomat/coding-standard: ^8.22
- squizlabs/php_codesniffer: ^3.13
Requires (Dev)
- drupal/coder: ^8.3.31
- phpunit/phpunit: ^11.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
PHP_CodeSniffer sniffs that bring Drupal projects closer to the code in Drupal core.
The Drupal coding standards and Coder cover a lot, but much of what makes core code look like core code is either written down without being checked, or not written down at all. This standard fills some of those gaps:
- Rules that the coding standards state but Coder does not check, such as
wrapping comments as close to 80 characters as possible, or documenting every
parameter with
@param. - Conventions that core follows almost everywhere without a written rule, such
as
protectedinstead ofprivate. - Practices that keep code readable for people and for static analysis, such as
typed variables for services from
\Drupal::service().
Each sniff is independent. Pick the ones that fit your project, or start from the strict setup that combines them with Coder and Slevomat sniffs.
Table of contents
Requirements
- PHP 8.3 or later.
- PHP_CodeSniffer 3.13 or later.
- Slevomat Coding Standard 8.22 or later. Several sniffs build on its helper classes. Composer installs it.
Installation
$ composer require --dev pfrenssen/drupal-sniffs
The PHP_CodeSniffer Standards Composer Installer
registers the standard with PHP_CodeSniffer. Check that PFrenssenDrupalSniffs
is in the list:
$ vendor/bin/phpcs -i The installed coding standards are ..., Drupal, DrupalPractice, SlevomatCodingStandard and PFrenssenDrupalSniffs
If Composer asks whether to trust the
dealerdirect/phpcodesniffer-composer-installer plugin, allow it. Drupal
projects that use Coder allow it already.
Usage
Reference the sniffs you want in your phpcs.xml.dist, next to the Drupal
standards:
<rule ref="Drupal"/> <rule ref="DrupalPractice"/> <rule ref="PFrenssenDrupalSniffs.Commenting.DocCommentFill"/> <rule ref="PFrenssenDrupalSniffs.Classes.DisallowPrivateVisibility"/>
<rule ref="PFrenssenDrupalSniffs"/> enables every sniff at once. Because some
sniffs enforce choices that not every project shares, such as
DisallowMarkTestSkipped,
picking sniffs one by one is the recommended approach.
Sniffs marked 🔧 fix their violations with phpcbf:
$ vendor/bin/phpcbf
Sniffs
| Sniff | 🔧 | Purpose |
|---|---|---|
| Classes.DisallowPrivateVisibility | protected instead of private, as in core. |
|
| Commenting.DocCommentFill | 🔧 | Wraps doc comments as close to 80 characters as possible. |
| Commenting.InlineCommentFill | 🔧 | Wraps // comments as close to 80 characters as possible. |
| Commenting.RequireFunctionDocTags | @param and @return in every function doc comment. |
|
| ControlStructures.RequireCompactTernary | 🔧 | No multiline ternary that fits on one line. |
| ControlStructures.RequireEmptyForNullOrEmptyString | 🔧 | empty($x) instead of $x === NULL || $x === ''. |
| Drupal.DrupalServiceFacade | Typed variables for \Drupal::service(). |
|
| Functions.RequireCompactCall | 🔧 | No multiline call that fits on one line. |
| PHPUnit.DisallowMarkTestSkipped | No skipped tests. | |
| PHPUnit.DisallowRoleCreationInExistingSiteTests | Real roles for users in ExistingSite tests. |
Classes
PFrenssenDrupalSniffs.Classes.DisallowPrivateVisibility
Forbids the private keyword on constants, properties, promoted constructor
properties and methods.
Why. Drupal is a framework that contrib and custom code extend by
subclassing. Core declares its class members protected so that a subclass can
change one method without copying the class: Drupal 11.4 has more than 20,000
protected members against fewer than 900 private ones. A private member in a
module forces everyone who needs to change it to copy or patch the code.
When to use it. In modules and themes that other code may extend, which in Drupal is almost all of them. Leave it out for code that deliberately seals its internals, such as a library with a strict backward compatibility policy.
// Reported. private function buildLabel(): string {} // Correct. protected function buildLabel(): string {}
Error code: PrivateForbidden.
Commenting
PFrenssenDrupalSniffs.Commenting.DocCommentFill
Reports a doc comment line that wraps too early: the first word of the next line would still fit within the line limit. The fixer moves as many words up as fit.
Why. The Drupal documentation standards require that "lines containing comments (including docblocks) must wrap as close to 80 characters as possible without going over". Coder checks only the "without going over" half, so lines shortened by later edits stay short.
What is left alone. The sniff compares two lines only when both are running text of the same paragraph. It skips:
- tag lines (
@param,@return, ...) and the line before a tag; - list items (
-,*,+,1.), table rows (|) and markup (<); - a line that ends with a colon, because it introduces a list or an example;
@code/@endcode,<code>and<pre>blocks;- multiline type expressions, such as
array{...}shapes in tags; - Doctrine annotations, such as
@ContentEntityType(...); - lines whose text is indented differently from the next one.
// Reported: "the" fits on the line above. /** * Loads the configuration of the * current site. */ // Correct. /** * Loads the configuration of the current site. */
| Property | Default | Description |
|---|---|---|
lineLimit |
80 |
The maximum line length, including indentation. |
Error code: Underfilled.
PFrenssenDrupalSniffs.Commenting.InlineCommentFill
The same check and fix as
DocCommentFill, for runs of
// comments. A run is a group of // comments on consecutive lines in the
same column, each on a line of its own. A comment after code on the same line is
never part of a run.
// Reported. // Rebuild the router so that the new // route is available. // Correct. // Rebuild the router so that the new route is available.
| Property | Default | Description |
|---|---|---|
lineLimit |
80 |
The maximum line length, including indentation. |
Error code: Underfilled.
PFrenssenDrupalSniffs.Commenting.RequireFunctionDocTags
Requires a function doc comment to have at least one @param tag when the
function has parameters, and a @return tag when it declares a return type
other than void.
Why. The Drupal documentation standards require that "each parameter of a
function must be documented with a @param tag" and that "if a function has a
return value, it must be documented with a @return tag". Coder validates tags
that are present, but reports nothing when a doc comment has none at all: a
one-line summary passes. This sniff closes that gap.
What is exempt, following the exceptions in the standards and common practice in core:
- doc comments with
{@inheritdoc}; - hook implementations, recognized by "Implements hook_" in the doc comment;
- constructors, whose parameters are documented by the properties they set;
test*()methods of*Testclasses;- functions in
*.post_update.phpfiles; - functions without a doc comment, which
Drupal.Commenting.FunctionCommentreports already.
// Reported twice: no @param, no @return. /** * Formats a price. */ function mymodule_format_price(float $amount): string {} // Correct. /** * Formats a price. * * @param float $amount * The amount in Swiss francs. * * @return string * The formatted price. */ function mymodule_format_price(float $amount): string {}
Error codes: MissingParam, MissingReturn.
Control structures
PFrenssenDrupalSniffs.ControlStructures.RequireCompactTernary
Reports a ternary operator spread over several lines when its single-line form fits within the line length limit, and puts it on one line.
Why. Core writes a ternary on one line unless it does not fit. Multiline ternaries usually appear when code is shortened after the fact or produced by a formatter, and they make a simple choice look like a complex one.
What is left alone. Short ternaries (?:), ternaries with a nested ternary
in their then branch, and ternaries that contain comments, closures, arrow
functions, heredocs or multiline strings.
// Reported. $label = $entity->isPublished() ? $this->t('Published') : $this->t('Unpublished'); // Correct. $label = $entity->isPublished() ? $this->t('Published') : $this->t('Unpublished');
| Property | Default | Description |
|---|---|---|
maxLineLength |
160 |
The maximum length of the single-line form, including indentation and the code before and after the ternary on the same line. |
Error code: RequiredCompactTernary.
PFrenssenDrupalSniffs.ControlStructures.RequireEmptyForNullOrEmptyString
Reports an if, elseif or while condition that compares one operand with
both NULL and an empty string, and replaces the pair with empty():
| Condition | Fix |
|---|---|
$x === NULL || $x === '' |
empty($x) |
$x !== NULL && $x !== '' |
!empty($x) |
Both operand orders ('' === $x) and pairs inside nested parentheses are
detected.
Why. The pair of comparisons says "has no value", which empty() says in
one call.
Caution. empty() also treats 0, '0', FALSE and [] as empty. When
'0' is a valid value, for example a user-entered string, keep the explicit
comparisons and suppress the sniff on that line.
Error codes: NullOrEmptyStringComparison,
NotNullAndNotEmptyStringComparison.
Drupal
PFrenssenDrupalSniffs.Drupal.DrupalServiceFacade
Enforces two rules for services fetched with \Drupal::service():
- No method call directly on the result.
- When the result is assigned to a variable, the line above must hold an
inline
/** @var Type $variable */doc comment for that variable.
Why. \Drupal::service() returns mixed. Without a type, PHPStan cannot
check the calls made on the service, and an IDE can neither autocomplete them
nor find their usages. Core itself chains calls on \Drupal::service()
thousands of times; this sniff is stricter than core on purpose, for projects
that run static analysis on procedural code, such as .module, .install and
.theme files, where dependency injection is not available.
In classes, inject the service instead. DrupalPractice already reports
\Drupal calls in classes that support dependency injection.
// Reported: chained call. \Drupal::service('entity_type.manager')->getStorage('node'); // Reported: no @var doc comment. $entity_type_manager = \Drupal::service('entity_type.manager'); // Correct. /** @var \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager */ $entity_type_manager = \Drupal::service('entity_type.manager'); $entity_type_manager->getStorage('node');
Services with a dedicated method on \Drupal, such as \Drupal::entityTypeManager()
or \Drupal::currentUser(), have a declared return type and are not affected.
Prefer them where they exist.
Error codes: ChainedMethodCall, MissingVarAnnotation,
InvalidVarAnnotation.
Functions
PFrenssenDrupalSniffs.Functions.RequireCompactCall
Reports a function call, method call or new expression spread over several
lines when its single-line form fits within the line length limit, and puts it
on one line.
Why. Core writes a call on one line unless it does not fit. Unlike
SlevomatCodingStandard.Functions.RequireSingleLineCall, this sniff also
collapses calls with array arguments, so that a call with a short array, such as
$storage->loadByProperties(['type' => 'article']), is not spread over four
lines.
What is left alone.
- calls with comments, closures, arrow functions, heredocs, multiline strings or multiline nested calls in their arguments;
- calls nested in the arguments of another call, which is checked as a whole;
- attributes, such as
#[Hook(...)]; new static(...), so thatcreate()factory methods of classes that implementContainerInjectionInterfacekeep one argument per line, as in core.
// Reported. $nodes = $this->nodeStorage->loadByProperties( ['type' => 'article'], ); // Correct. $nodes = $this->nodeStorage->loadByProperties(['type' => 'article']);
| Property | Default | Description |
|---|---|---|
maxLineLength |
120 |
The maximum length of the single-line form, including indentation and the code before and after the call on the same line. |
Error code: RequiredCompactCall.
PHPUnit
PFrenssenDrupalSniffs.PHPUnit.DisallowMarkTestSkipped
Forbids calls of markTestSkipped().
Why. A skipped test passes in CI while it tests nothing. Skips added "for now" because a fixture or the environment is missing tend to stay, and the coverage they hide is lost without anyone noticing. A test that cannot run should fail, so that the missing fixture or environment is fixed, or be deleted.
When to use it. In projects that control their own test environment. Core
and contrib modules that run on several databases or PHP versions use
markTestSkipped() legitimately for tests that do not apply to the current
environment; this sniff does not suit them. Limit it to test code:
<rule ref="PFrenssenDrupalSniffs.PHPUnit.DisallowMarkTestSkipped"> <include-pattern>*/tests/src/*</include-pattern> </rule>
Error code: Forbidden.
PFrenssenDrupalSniffs.PHPUnit.DisallowRoleCreationInExistingSiteTests
Forbids creating user roles in the ExistingSite tests of Drupal Test Traits. It reports:
createRole(),createAdminRole()andgrantPermissions();Role::create();createUser()andsetUpCurrentUser()with permissions or with$adminset, becauseUserCreationTraitcreates a role for them.
Why. Saving or deleting a role is slow on a site with many contrib
modules, because they react to it. Admin Toolbar Extra Tools
(admin_toolbar_tools), for example, rebuilds all menu links on every insert,
update and delete of a role, which takes seconds on a site with a large menu. A
test pays this twice for each role it creates: once on creation and once on
cleanup. A test that gives its user an existing role pays nothing.
ExistingSite tests also run against the configuration of the site. A test that passes for a set of permissions that no role of the site has proves nothing about what the site's users can do.
What is checked. Files in tests/src/ExistingSite* directories only, such
as ExistingSite and ExistingSiteJavascript. Kernel and Functional tests run
on a fresh installation that has no roles to reuse, so they have to create
their own.
// Reported. $user = $this->createUser(['edit any article content']); // Correct. $user = $this->createUser([], NULL, FALSE, ['roles' => ['editor']]);
Error codes: CreateRole, CreateAdminRole, GrantPermissions, RoleCreate,
CreateUserWithPermissions, CreateUserAsAdmin,
SetUpCurrentUserWithPermissions, SetUpCurrentUserAsAdmin.
A strict setup
examples/phpcs.xml.dist is a complete, strict
ruleset for a Drupal project. It is distilled from the rulesets of the projects
these sniffs come from, and this package checks its own code with it. It
combines:
- Coder:
DrupalandDrupalPractice, with long array declarations allowed on one line (#3185082). - All sniffs of this package, with
DisallowMarkTestSkippedlimited totests/src. - Slevomat sniffs that align custom code with core:
| Sniff | What it enforces |
|---|---|
TypeHints.DeclareStrictTypes |
declare(strict_types=1); in every PHP file, with one blank line before and after. |
TypeHints.NullableTypeForNullDefaultValue |
?Foo $foo = NULL instead of Foo $foo = NULL. |
TypeHints.ReturnTypeHintSpacing |
): string, as core formats return types. |
TypeHints.ClassConstantTypeHint |
A type on every class constant. |
Classes.RequireConstructorPropertyPromotion |
Promoted constructor properties, as in current core code. |
Classes.RequireSingleLineMethodSignature |
Method signatures on one line; constructors keep one promoted property per line. |
Namespaces.ReferenceUsedNamesOnly |
use statements for namespaced names, including in attributes and for functions and constants; global names such as \Drupal and \DateTime stay fully qualified, as in core. |
Namespaces.AlphabeticallySortedUses |
Sorted use statements, including those added by the fixer of the sniff above. |
Commenting.ForbiddenAnnotations |
No @author, @copyright, @license, @package and similar tags that IDEs add and Drupal does not use. |
Commenting.ForbiddenComments |
No generated doc comments such as "Class Foo." or "Foo constructor.", and {@inheritdoc} instead of {@inheritDoc}. |
To use it, copy it to the root of the project and add the paths to check:
<file>web/modules/custom</file> <file>web/themes/custom</file>
Alternatively, reference it from your own ruleset, which keeps it up to date with this package:
<?xml version="1.0"?> <ruleset name="my_project"> <file>web/modules/custom</file> <file>web/themes/custom</file> <rule ref="vendor/pfrenssen/drupal-sniffs/examples/phpcs.xml.dist"/> </ruleset>
The example has no <file> entries of its own for this reason: PHP_CodeSniffer
adds the <file> entries of every referenced ruleset to the files to check.
Suppressing a sniff
Use the PHP_CodeSniffer annotations, with the full error code:
// phpcs:ignore PFrenssenDrupalSniffs.ControlStructures.RequireEmptyForNullOrEmptyString.NullOrEmptyStringComparison if ($value === NULL || $value === '') {
To turn off one error code project-wide, exclude it in the ruleset:
<rule ref="PFrenssenDrupalSniffs.Commenting.RequireFunctionDocTags"> <exclude name="PFrenssenDrupalSniffs.Commenting.RequireFunctionDocTags.MissingReturn"/> </rule>
Contributing
The package checks itself with the strict setup, and tests every sniff with PHPUnit:
$ composer install $ composer check
Each sniff has a test in tests/Sniffs/<Category>/<Name>SniffTest.php that runs
it on a fixture in tests/Sniffs/<Category>/data/<Name>.php. For a fixable
sniff, <Name>.fixed.php holds the expected result of the fixer. A new sniff
needs a test with fixtures for what it reports, for what it leaves alone, and
for its fixes.
New sniffs fit here when they align Drupal projects with the code of Drupal core, or with a rule of the Drupal coding standards that Coder does not check. A sniff that checks a written Drupal coding standard is a candidate for Coder itself; propose it there as well.
License
GPL-2.0-or-later, the license of Drupal core. See LICENSE.txt.