Skip to content

Instantly share code, notes, and snippets.

@dantleech
Last active October 21, 2021 21:22
Show Gist options
  • Save dantleech/571f3ef78af39a35528de90b9e1530bb to your computer and use it in GitHub Desktop.
Save dantleech/571f3ef78af39a35528de90b9e1530bb to your computer and use it in GitHub Desktop.
PHPStan Drupal Integration
$ 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
parameters:
bootstrap: ./docroot/phpstan_autoload.php
<?php
use Drupal\Console\Core\Utils\DrupalFinder;
use Drupal\Console\Bootstrap\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
$autoload = require_once __DIR__ . '/autoload.php';
$root = getcwd();
$drupalFinder = new DrupalFinder();
if (!$drupalFinder->locateRoot($root)) {
die('DrupalConsole must be executed within a Drupal Site.');
}
chdir($drupalFinder->getDrupalRoot());
$drupalKernel = DrupalKernel::createFromRequest(
Request::createFromGlobals(),
$autoload,
'prod',
true,
$drupalFinder->getDrupalRoot()
);
$drupalKernel->boot();
return $autoload;
@gogowitsch
Copy link

gogowitsch commented Oct 19, 2018

Thanks!

I had to add these lines to phpstan_autoload.php:

// Ensure that procedural dependencies are loaded as early as possible,
// since the error/exception handlers depend on them.
require_once __DIR__ . '/../web/core/modules/system/system.install';
require_once __DIR__ . '/../web/core/includes/common.inc';
require_once __DIR__ . '/../web/core/includes/file.inc';
require_once __DIR__ . '/../web/core/includes/install.inc';
require_once __DIR__ . '/../web/core/includes/schema.inc';
require_once __DIR__ . '/../web/core/includes/database.inc';
require_once __DIR__ . '/../web/core/includes/form.inc';
require_once __DIR__ . '/../web/core/includes/batch.inc';

// Load module basics (needed for hook invokes).
include_once __DIR__ . '/../web/core/includes/module.inc';
require_once __DIR__ . '/../web/core/includes/entity.inc'

For future readers, here is another article about PHPStan and Drupal: https://glamanate.com/blog/writing-better-drupal-code-static-analysis-using-phpstan

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment