Writing custom PHPStan rules for Drupal projects

Today, I watched a video recording of a session by Ondřej Mirtes - the creator of PHPStan - on writing custom rules for PHPStan.

After explaining how to write them, he showed some examples of custom rules - one of which was ensuring a Person class couldn't be created outside of a PersonRepository class.

This seemed straightforward so I thought about how I could do something similar within my Drupal automated testing email course to check my Drupal code.

Similar to Ondřej's example, I wondered if I could enforce that no post nodes should be created outside of the PostBuilder class by searching for any code like Node::create(['type' => 'post']).

I was able to get a version working quickly and have posted it as a gist.

I'm sure some improvements can be made, but it was a successful experiment and something I can see me using more in the future.

- Oliver

Was this interesting?

Sign up here and get more like this delivered straight to your inbox every day.

About me

Picture of Oliver

I'm an Acquia-certified Drupal Triple Expert with 17 years of experience, an open-source software maintainer and Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.