In the early days of Drupal 9, most folks were only using PHPStan on their Drupal sites via drupal-check for deprecation checks. I am excited to see more folks using PHPStan directly with phpstan-drupal to perform static analysis and deprecation checks. However, folks are starting to hit some of the DrupalWTF's when performing static analysis on a magical code base
MAGIC?! Yes, Drupal has a lot of magical return types that are not typed. Inside phpstan-drupal, we try to help out as much as possible, but we cannot know everything.
Take a typical implementation of hook_ENTITY_TYPE_insert
.
function mymodule_node_insert(\Drupal\Entity\EntityInterface $node) {
// Do some node stuff
}
Notice something? The $node
parameter is type hinted at EntityInterface
. This is true because Node
implements NodeInterface,
which extends EntityInterface
. However, anything on the NodeInterface
(or its other parent interfaces) is technically unavailable.
Your hook should be clear on the entity it receives.
function mymodule_node_insert(\Drupal\node\NodeInterface $node) {
// Do some node stuff
}
Then PHPStan will understand what kind of object $node
is.
The problem I am facing is that there are many more of these support requests coming in, saying that static analysis is broken. There hasn't been a user guide for phpstan-drupal. A significant part of that is because documentation collaboration for projects on GitHub is horrible. Wikis are either public or modified by contributors, and contributors can manage code. No thanks, GitHub.
But! We do have Drupal.org. I have created a new PHPStan guide under the Developer Tools section to document Drupal + PHPStan. I will do my best to begin adding information here. That would be amazing if the community would like to help step in with flushing out tips for type hinting. I am mostly happy to have somewhere to link folks now.
The other fantastic news is that folks have been pushing hard to get Drupal core running against PHPStan at level 0. So the documentation will help out with Drupal core as well.
Want more? Sign up for my weekly newsletter