$ composer require phpstan/phpstan
Drupal dynamically adds to the class autoloader at runtime, so it is necessary to bootstrap Drupal in order that it is fully populated. Note that this may require that the database be accessible (i.e. may be problematic when working with Docker). This is why we use a custom autoload file below.
$ ./bin/phpstan analyse --level=7 -c phpstan.neon docroot/modules/custom
Thanks!
I had to add these lines to phpstan_autoload.php:
For future readers, here is another article about PHPStan and Drupal: https://glamanate.com/blog/writing-better-drupal-code-static-analysis-using-phpstan