Doctrine extensions for PHPStan
This extension provides following features:
findBy*, findOneBy* and countBy* methods on EntityRepository.findBy, findBy*, findOneBy, findOneBy*, count and countBy* method calls.EntityRepository correctly in phpDocs for further type inference of methods called on the repository.Doctrine\ORM\EntityManager::getRepository().Doctrine\ORM\EntityManager::find, getReference and getPartialReference when Foo::class entity class name is provided as the first argumentmatching method on Doctrine\Common\Collections\Collection. This can be turned off by setting parameters.doctrine.allCollectionsSelectable to false.allowNullablePropertyForRequiredField: true setting.Doctrine\ORM\Query::getResult, getOneOrNullResult, getSingleResult, toIterable and execute in HYDRATE_OBJECT mode (see below).final entity classes that can cause problems with Doctrine proxy generation (allowed when native lazy objects are enabled).final entity constructors that can cause problems with Doctrine proxy generation.EntityManager::flush() (ORMException, UniqueConstraintViolationException).Timestampable, Blameable, Slug) are recognized for dead code detection.Collection::first() and Collection::last() return types from T|false to T when isEmpty() is false.To use this extension, require it in Composer:
composer require --dev phpstan/phpstan-doctrineIf you also install phpstan/extension-installer then you're all set!
Manual installation
If you don't want to use phpstan/extension-installer, include extension.neon in your project's PHPStan config:
includes:
- vendor/phpstan/phpstan-doctrine/extension.neonIf you're interested in DQL/QueryBuilder validation, include also rules.neon (you will also need to provide the objectManagerLoader, see below):
includes:
- vendor/phpstan/phpstan-doctrine/rules.neonIf your repositories have a common base class, you can configure it in your phpstan.neon and PHPStan will see additional methods you define in it:
parameters:
doctrine:
ormRepositoryClass: MyApp\Doctrine\BetterEntityRepository
odmRepositoryClass: MyApp\Doctrine\BetterDocumentRepositoryYou can opt in for more advanced analysis by providing the object manager from your own application. This will enable DQL validation:
parameters:
doctrine:
objectManagerLoader: tests/object-manager.phpExample for Symfony 4:
// tests/object-manager.php
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();Example for Symfony 5:
// tests/object-manager.php
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();If your application uses multiple entity managers, return the Doctrine manager registry from the loader. PHPStan Doctrine will use it to pick the object manager that owns the entity being analysed:
// tests/object-manager.php
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');This extension can infer the result type of DQL queries when an objectManagerLoader is provided.
Examples:
$query = $entityManager->createQuery('SELECT u FROM Acme\User u');
$query->getResult(); // array
$query = $entityManager->createQuery('SELECT u.id, u.email, u.name FROM Acme\User u');
$query->getResult(); // array
$query = $entityManager->createQuery('
SELECT u.id, u.email, COALESCE(u.name, "Anonymous") AS name
FROM Acme\User u
');
$query->getSingleResult(Query::HYDRATE_OBJECT); // array{id: int, email: string, name: string}>
$query = $entityManager->createQueryBuilder()
->select('u')
->from(User::class, 'u')
->getQuery();
$query->getResult(); // arrayQueries are analyzed statically and do not require a running database server. This makes use of the Doctrine DQL parser and entities metadata.
Most DQL features are supported, including GROUP BY, INDEX BY, DISTINCT, all flavors of JOIN, arithmetic expressions, functions, aggregations, NEW, etc. Sub queries are not yet supported (infered type will be mixed).
Whether e.g. SUM(e.column) is fetched as float, numeric-string or int highly depends on drivers, their setup and PHP version.
This extension autodetects your setup and provides quite accurate results for pdo_mysql, mysqli, pdo_sqlite, sqlite3, pdo_pgsql and pgsql.
The getResult method is supported when called without argument, or with the hydrateMode argument set to Query::HYDRATE_OBJECT:
$query = $entityManager->createQuery('SELECT u FROM Acme\User u');
$query->getResult(); // array
$query->getResult(Query::HYDRATE_OBJECT); // arrayThe methods getOneOrNullResult, getSingleResult, toIterable, and execute are supported when the hydrateMode argument is explicitly set to Query::HYDRATE_OBJECT:
$query = $entityManager->createQuery('SELECT u FROM Acme\User u');
$query->getOneOrNullResult(); // mixed
$query->getOneOrNullResult(Query::HYDRATE_OBJECT); // UserThis is due to the design of the Query class preventing from determining the hydration mode used by these functions unless it is specified explicitly during the call.
Not every QueryBuilder can be statically analysed, here are few advices to maximize type inferring:
select/join/from/set)You can enable reporting of places where inferring is unavailable by:
parameters:
doctrine:
reportDynamicQueryBuilders: trueIf your application uses custom Doctrine types, you can write your own type descriptors to analyse them properly.
Type descriptors implement the interface PHPStan\Type\Doctrine\Descriptors\DoctrineTypeDescriptor which looks like this:
walkSimpleArithmeticExpression($this->arithmeticExpression) . ')';
}
public function parse(Parser $parser): void
{
$parser->match(TokenType::T_IDENTIFIER);
$parser->match(TokenType::T_OPEN_PARENTHESIS);
$this->arithmeticExpression = $parser->SimpleArithmeticExpression();
$parser->match(TokenType::T_CLOSE_PARENTHESIS);
}
public function getReturnType(): Type
{
return Type::getType(Types::INTEGER);
}
}
Stub files in phpstan-doctrine come with many parameters marked with literal-string. This is a security-focused type that only allows literal strings written in code to be passed into these parameters.
This reduces risk of SQL injection because dynamic strings from user input are not accepted in place of literal-string.
An example where this type is used is $sql parameter in Doctrine\Dbal\Connection::executeQuery().
To enable this advanced type in phpstan-doctrine, use this configuration parameter:
parameters:
doctrine:
literalString: trueNo open issues yet, or sync has not completed.