Tighten up your Drupal code using PHPStan

Catch me (virtually) at SFDUG in March

I’ll be presenting this same talk virtually at the San Fransisco Drupal Users Group meetup on March 10th. I will be updating my slides based on feedback and discussions from my talk at FLDC.

SFDUG - March 10 - Tighten up your Drupal code using PHPStan | Meetup

A quick history lesson on drupal-check

Part of this is my fault. The phpstan/extension-installer package did not exist. Setting up PHPStan + phpstan-drupal wasn’t difficult, but you had to make sure to include the extension configuration files in your phpstan.neon for phpstan-drupal and phpstan-deprecation-rules. Something like this:

parameters:
level: 0
includes:
- vendor/phpstan/phpstan-deprecation-rules/rules.neon
- vendor/mglaman/phpstan-drupal/extension.neon

The benefits of PHPStan

Two main takeaways could be taken away from my session, I believe:

  1. Running PHPStan at level 0 is not enough, and we all should be running at level 2 for catching deprecations
  2. You should add PHPStan as part of your development workflow to help your team leads and junior developers

Why do we need to run PHPStan at level 2?

Level 2 begins to report undefined methods called on classes. The slides go through the example of a typo for a call to an expected isPublished method in a hook_node_insert hook. PHPStan does not report the typo until we go to level 2. When the typo is fixed, assuming that is the problem, PHPStan may say that it still does not exist. This is because the hook has the default type of EntityInterface when it should be NodeInterface, which has isPublished.

Helping junior developers grow by using PHPStan

Start using PHPStan as part of your development flow. It needs to be part of your continuous integration process. It needs to run at least at level 5. I'm not going to explain in depth what rules 1-5 provide. You can see that in the documentation for PHPStan: https://phpstan.org/user-guide/rule-levels.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Matt Glaman

Matt Glaman

178 Followers

Open source developer, working with Drupal and building Drupal Commerce.