PHPStan in Drupal core

Last updated on
11 March 2024

This documentation needs review. See "Help improve this page" in the sidebar.

Drupal Core uses PHPStan to help introduce strict and informative types to its codebase. Its configuration file can be found in core/phpstan.neon.dist. Drupal Core uses the PHPStan extension installer to automatically load installed PHPStan libraries into its configuration. The following extensions are used at the time of writing:

Additionally Drupal core currently enables the "bleeding edge" configuration of PHPStan to benefit from significant performance improvements.

PHPStan Baseline

Because PHPStan requires analyzing the entire codebase and it's recommended to run on higher levels even if there are errors, it's not possible for Drupal to fix all issues immediately. To ensure that new code can be added against higher standards we make use of the PHPStan baseline feature. This allows us to ignore known errors while PHPStan helps us ensure new code and improvements to existing code are correctly typed. For performance reasons Drupal generates the baseline in PHP format.

Updating the baseline

When contributing code to Drupal you may fix type errors which cause PHPStan to tell you that ignored errors could no longer be found. This requires regenerating the baseline to remove the fixed errors from it. To regenerate the baseline, run the following from the root of the Drupal repository:

vendor/bin/phpstan analyze --configuration=./core/phpstan.neon.dist --memory-limit=-1 --generate-baseline=core/.phpstan-baseline.php

Once you've created a merge request the GitLab CI will also include a regenerated PHPStan baseline as artifact of any failed PHPStan job. In case you forgot to remove ignored errors that are now fixed you can download the baseline and commit it.

Resolving merge conflicts in the baseline

In case your Merge Request is blocked by a conflict in the PHPStan baseline, the recommended way to resolve the conflict is to let PHPStan regenerate the baseline on top of the branch you're merging with, rather than manually resolving conflicts.

# From the point of conflict (e.g. caused by `git rebase` or `git merge`)
git checkout <target-branch> -- core/.phpstan-baseline.php
vendor/bin/phpstan analyze --configuration=./core/phpstan.neon.dist --memory-limit=-1 --generate-baseline=core/.phpstan-baseline.php

# Use git to mark the merge conflict as resolved and continue

Tags

Help improve this page

Page status: Needs review

You can: