phpstan-drupal
Extension for PHPStan to allow analysis of Drupal code.
PHPStan is able to discover symbols by using autoloading provided
by Composer. However, Drupal does not provide autoloading information for modules and themes. This project registers
those namespaces so that PHPStan can properly discover symbols in your Drupal code base automatically.
[!NOTE]
With Drupal 11.2, Drupal core is now using PHPStan 2.0. The 1.x branch of phpstan-drupal will be supported until
Drupal 10 loses security support when Drupal 12 is released.
Sponsors

Would you like to sponsor?
Usage
When you are using phpstan/extension-installer, phpstan.neon will be automatically included.
Manual installation
If you don't want to use phpstan/extension-installer, include both files in your project's PHPStan config:
includes:
- vendor/mglaman/phpstan-drupal/extension.neon
- vendor/mglaman/phpstan-drupal/rules.neon
extension.neon adds Drupal's types and services. rules.neon adds the Drupal rules. Two of those rules also load files for the rest of the analysis: LoadIncludes loads the file a ModuleHandlerInterface::loadInclude() call includes, and ModuleLoadInclude does the same for module_load_include(). Without rules.neon, functions from those files are reported as not found:
Function locale_translation_flush_projects not found.
Getting help
Ask for assistance in the discussions or #phpstan channel on Drupal Slack.
Excluding tests from analysis
To exclude tests from analysis, add the following parameter
parameters:
excludePaths:
- *Test.php
- *TestBase.php
Deprecation testing
This project depends on phpstan/phpstan-deprecation-rules which adds deprecation rules. We provide Drupal-specific
deprecated scope resolvers.
phpstan-deprecation-rules reports code marked with @deprecated. Drupal also deprecates code that has no such tag, so phpstan-drupal adds its own rules for it:
| Deprecation |
Identifier |
Getting a service that is deprecated in a *.services.yml file with \Drupal::service() |
staticServiceDeprecatedService.deprecated |
Getting a deprecated service from the container with get() |
getDeprecatedService.deprecated |
The context key in a plugin annotation |
pluginAnnotationContextDefinitions.useContextDefinitionsKey |
A translatable category in a @FieldType annotation |
fieldTypeCategory.translatable |
| A plugin manager that only supports annotation discovery |
pluginManager.attributeDiscoveryMissing, pluginManager.attributeDiscoveryMissingDefault |
These rules run whenever phpstan-deprecation-rules is loaded, and they turn off with it. They don't have drupal.rules.* parameters. To ignore one, use its identifier in ignoreErrors.
Plugin managers without attribute discovery
Drupal 12 throws an exception for plugin managers that only support annotation discovery. Drupal 11.2 deprecated them at runtime with @trigger_error(). phpstan-drupal reports a DefaultPluginManager subclass that passes an annotation class, instead of an attribute class, as the fifth argument to parent::__construct(). It uses two identifiers:
pluginManager.attributeDiscoveryMissing: the argument is a ::class constant, a string, or a local variable holding one.
pluginManager.attributeDiscoveryMissingDefault: the argument comes from a static property or a constructor parameter default. A subclass or caller may override the default.
To fix a reported manager, pass the attribute class as the fifth argument and keep the annotation class as the sixth. This works on Drupal 10.2 and later. The rules do nothing on Drupal versions older than 10.2, which don't have attribute discovery.
The rules only check the argument's value. They also report managers that pick the class at runtime, which work on Drupal 12:
parent::__construct(
'Plugin/Example',
$namespaces,
$module_handler,
ExampleInterface::class,
class_exists(Example::class) ? Example::class : ExampleAnnotation::class,
);
The same applies to a version_compare() branch that passes the annotation class only on older Drupal versions. Ignore these by identifier:
parameters:
ignoreErrors:
-
identifier: pluginManager.attributeDiscoveryMissing
path: src/ExamplePluginManager.php
To only handle deprecation testing, use a phpstan.neon like this:
parameters:
customRulesetUsed: true
reportUnmatchedIgnoredErrors: false
# Ignore phpstan-drupal extension's rules.
ignoreErrors:
- '#\Drupal calls should be avoided in classes, use dependency injection instead#'
- '#Plugin definitions cannot be altered.#'
- '#Missing cache backend declaration for performance.#'
- '#Plugin manager has cache backend specified but does not declare cache tags.#'
includes:
- vendor/mglaman/phpstan-drupal/extension.neon
- vendor/phpstan/phpstan-deprecation-rules/rules.neon
To disable deprecation rules while using phpstan/extension-installer, you can do the following:
{
"extra": {
"phpstan/extension-installer": {
"ignore": [
"phpstan/phpstan-deprecation-rules"
]
}
}
}
See the extension-installer documentation for more information: https://github.com/phpstan/extension-installer#ignoring-a-particular-extension
Adapting to your project
Customizing rules
Default rules promoted in 2.1.0
As of 2.1.0, the following rules are enabled by default. Disable any of them individually if they don't fit your project:
parameters:
drupal:
rules:
# Enforces that OOP hook implementations using the Hook attribute have the
# correct method signature for hook_form_alter, hook_form_FORM_ID_alter, etc.
# Requires Drupal 10.3+ (Hook attribute).
hookFormAlterRule: false
# Flags non-abstract test classes whose names do not end with "Test".
testClassSuffixNameRule: false
# Flags properties that are private or read-only in classes using
# DependencySerializationTrait, which does not support them.
dependencySerializationTraitPropertyRule: false
# Flags calls to AccessResult static methods (::allowed(), ::forbidden(), etc.)
# whose argument type already makes the condition always true or always false.
accessResultConditionRule: false
# Flags addCacheableDependency() calls whose argument does not implement
# CacheableDependencyInterface.
cacheableDependencyRule: false
# Flags logger channel objects (from LoggerChannelFactoryInterface::get()) that
# are assigned to a property in a class using DependencySerializationTrait,
# which cannot serialize logger channels correctly.
loggerFromFactoryPropertyAssignmentRule: false
# Flags direct injection of EntityStorageInterface (or a subtype) into a
# constructor. Inject EntityTypeManagerInterface and call getStorage() instead.
entityStorageDirectInjectionRule: false
# Flags direct use of Symfony\Component\Yaml\Yaml::parse() on Drupal-controlled
# YAML files, which should go through Drupal's YAML parser.
symfonyYamlParseRule: false
# Flags cacheability issues in entity list builder and entity operation hooks.
entityOperationsCacheabilityRule: false
[!NOTE]
hookRules was renamed to hookFormAlterRule in 2.1.0 — update your configuration if you referenced it explicitly.
Legacy rules made configurable in 2.2.0
The following rules were previously always on. They remain enabled by default, but can now be disabled individually:
parameters:
drupal:
rules:
# Flags calls to discouraged functions such as Devel's debugging
# functions (dpm, dsm, kint, ...) and fnmatch.
discouragedFunctionsRule: false
# Flags \Drupal static calls inside classes that should use
# dependency injection instead.
globalDrupalDependencyInjectionRule: false
# Flags plugin managers that do not set a cache backend.
pluginManagerSetsCacheBackendRule: false
# Validates module_load_include() calls and loads the include for
# the rest of the analysis.
moduleLoadInclude: false
# Validates ModuleHandlerInterface::loadInclude() calls and loads
# the include for the rest of the analysis.
loadIncludes: false
Disabling checks for extending @internal classes
You can disable the ClassExtendsInternalClassRule rule by adding the following to your phpstan.neon:
parameters:
drupal:
rules:
classExtendsInternalClassRule: false
Disabling extensions
You can disable various extensions. This is useful when contributing to Drupal Core to improve its types.
parameters:
drupal:
extensions:
entityFieldsViaMagicReflection: true
entityFieldMethodsViaMagicReflection: true
entityQuery: true
entityRepository: true
stubFiles: true
All options are enabled by default.
[!NOTE]
Content entities are registered as PHPStan universal object crates, because ContentEntityBase::__get() accepts any property name. With entityFieldsViaMagicReflection disabled, a field access such as $node->field_foo is typed mixed instead of being reported as an undefined property.
Class resolver return types
ClassResolverInterface::getInstanceFromDefinition() and \Drupal::classResolver() calls are narrowed to the type of the passed class name or service ID. The return value is not guaranteed at runtime: the container is checked first, and a service definition can substitute a different class. Disable the narrowing to keep instanceof assertions meaningful:
parameters:
drupal:
classResolverReturnType: false
Enabled by default. When disabled, calls fall back to the declared object return type.
Bleeding-edge checks
bleedingEdge.neon enables hook deprecation checks against .api.php files and stricter service-container checking. New rules land here first before graduating to the default ruleset in a minor release. Deprecation rules don't: they run whenever phpstan-deprecation-rules is loaded.
includes:
- vendor/mglaman/phpstan-drupal/bleedingEdge.neon
What it currently enables:
checkCoreDeprecatedHooksInApiFiles — reports hook implementations deprecated in Drupal core .api.php files
checkContribDeprecatedHooksInApiFiles — reports hook implementations deprecated in contrib module .api.php files
configGetUnknownKeyRule — reports Config::get() calls with a key that isn't in the config schema. See "Config schema-based checks".
formApiCallbackRule — reports Form API callbacks that fail at runtime. See "Form API callback checks".
lazyBuilderRule — reports #lazy_builder render arrays that break the renderer's rules. See "#lazy_builder checks".
[!NOTE]
checkDeprecatedHooksInApiFiles is deprecated. Use checkCoreDeprecatedHooksInApiFiles and checkContribDeprecatedHooksInApiFiles instead.
[!NOTE]
containerHasAlwaysTrue: false graduated from bleeding edge to the default in 2.1.0. ContainerInterface::has() returns bool instead of always-true for known services, so conditional service guards stay meaningful. Restore the old inference with:
parameters:
drupal:
bleedingEdge:
containerHasAlwaysTrue: true
Config schema-based checks (experimental)
Two opt-in features use Drupal's config schema files to analyze Config::get() calls. Both only act on config objects whose schema has the FullyValidatable constraint, since only those schemas are guaranteed complete. Schema files are parsed lazily on first use, so there is no cost when the features are disabled.
parameters:
drupal:
# Narrows Config::get() return types from the config schema, e.g.
# \Drupal::config('system.cron')->get('logging') resolves to bool|null
# instead of mixed. Types are nullable because any key can be absent
# at runtime.
configGetReturnType: true
rules:
# Reports Config::get() calls with a key that does not exist in the
# config schema, catching typos at analysis time.
configGetUnknownKeyRule: true
Recognized call patterns:
\Drupal::config('...')->get('...')
$configFactory->get('...')->get('...')
$configFactory->getEditable('...')->get('...')
$this->config('...')->get('...') in classes using ConfigFormBaseTrait
The config name and key must be literal strings. Config entity schemas with wildcard names (e.g. block.block.*