The phpstan/phpstan-doctrine is an extension for PHPStan that provides various features related to the Doctrine ORM (Object-relational mapping) tool. This includes DQL (Doctrine Query Language) validation for parsing errors, unknown entity classes, and unknown persistent fields, QueryBuilder validation, and recognition of magic methods on EntityRepository, among others. It also provides correct return types for certain Doctrine ORM methods and supports Doctrine ODM (Object Document Mapper). Additionally, it can analyze discrepancies between entity column types and property field types and infer result types of DQL queries if an object manager from the application is provided.
To use the phpstan/phpstan-doctrine, install it in Composer with the command composer require --dev phpstan/phpstan-doctrine
. If you're using phpstan/extension-installer, it's all you need to do. Otherwise, you have to include 'extension.neon' and optional 'rules.neon' in your project's PHPStan config. Here is a basic usage example:
includes:
- vendor/phpstan/phpstan-doctrine/extension.neon
Further configuration can be done in your phpstan.neon
file to specify your repositories' common base class. More advanced analysis can be enabled by providing the object manager of your application to validate DQL. Here is a brief code example of this:
parameters:
doctrine:
objectManagerLoader: tests/object-manager.php
Here is Symfony 4 & 5 examples of object-manager.php:
For Symfony 4:
use App\Kernel;
require __DIR__ . '/../config/bootstrap.php';
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$kernel->boot();
return $kernel->getContainer()->get('doctrine')->getManager();
For Symfony 5:
use App\Kernel;
use Symfony\Component\Dotenv\Dotenv;
require __DIR__ . '/../vendor/autoload.php';
(new Dotenv())->bootEnv(__DIR__ . '/../.env');
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$kernel->boot();
return $kernel->getContainer()->get('doctrine')->getManager();
The main documentation for phpstan/phpstan-doctrine is found within its GitHub repository (https://github.com/phpstan/phpstan-doctrine.git). It provides comprehensive explanations for the installation process, configuration options, query type inference, and more.