phpstan / phpstan-doctrine
Doctrine extensions for PHPStan
Installs: 44 842 093
Dependents: 982
Suggesters: 4
Security: 0
Stars: 599
Watchers: 10
Forks: 98
Open Issues: 86
Type:phpstan-extension
Requires
- php: ^7.4 || ^8.0
- phpstan/phpstan: ^2.0.3
Requires (Dev)
- cache/array-adapter: ^1.1
- composer/semver: ^3.3.2
- cweagans/composer-patches: ^1.7.3
- doctrine/annotations: ^2.0
- doctrine/collections: ^1.6 || ^2.1
- doctrine/common: ^2.7 || ^3.0
- doctrine/dbal: ^3.3.8
- doctrine/lexer: ^2.0 || ^3.0
- doctrine/mongodb-odm: ^2.4.3
- doctrine/orm: ^2.16.0
- doctrine/persistence: ^2.2.1 || ^3.2
- gedmo/doctrine-extensions: ^3.8
- nesbot/carbon: ^2.49
- php-parallel-lint/php-parallel-lint: ^1.2
- phpstan/phpstan-phpunit: ^2.0
- phpstan/phpstan-strict-rules: ^2.0
- phpunit/phpunit: ^9.6.20
- ramsey/uuid: ^4.2
- symfony/cache: ^5.4
Conflicts
- doctrine/collections: <1.0
- doctrine/common: <2.7
- doctrine/mongodb-odm: <1.2
- doctrine/orm: <2.5
- doctrine/persistence: <1.3
- 2.0.x-dev
- 2.0.1
- 2.0.0
- 1.5.x-dev
- 1.5.7
- 1.5.6
- 1.5.5
- 1.5.4
- 1.5.3
- 1.5.2
- 1.5.1
- 1.5.0
- 1.4.x-dev
- 1.4.8
- 1.4.7
- 1.4.6
- 1.4.5
- 1.4.4
- 1.4.3
- 1.4.2
- 1.4.1
- 1.4.0
- 1.3.x-dev
- 1.3.69
- 1.3.68
- 1.3.67
- 1.3.66
- 1.3.65
- 1.3.64
- 1.3.63
- 1.3.62
- 1.3.61
- 1.3.60
- 1.3.59
- 1.3.58
- 1.3.57
- 1.3.56
- 1.3.55
- 1.3.54
- 1.3.53
- 1.3.52
- 1.3.51
- 1.3.50
- 1.3.49
- 1.3.48
- 1.3.47
- 1.3.46
- 1.3.45
- 1.3.44
- 1.3.43
- 1.3.42
- 1.3.41
- 1.3.40
- 1.3.39
- 1.3.38
- 1.3.37
- 1.3.36
- 1.3.35
- 1.3.34
- 1.3.33
- 1.3.32
- 1.3.31
- 1.3.30
- 1.3.29
- 1.3.28
- 1.3.27
- 1.3.26
- 1.3.25
- 1.3.24
- 1.3.23
- 1.3.22
- 1.3.21
- 1.3.20
- 1.3.19
- 1.3.18
- 1.3.17
- 1.3.16
- 1.3.15
- 1.3.14
- 1.3.13
- 1.3.12
- 1.3.11
- 1.3.10
- 1.3.9
- 1.3.8
- 1.3.7
- 1.3.6
- 1.3.5
- 1.3.4
- 1.3.3
- 1.3.2
- 1.3.1
- 1.3.0
- 1.2.11
- 1.2.10
- 1.2.9
- 1.2.8
- 1.2.7
- 1.2.6
- 1.2.5
- 1.2.4
- 1.2.3
- 1.2.2
- 1.2.1
- 1.2.0
- 1.1.1
- 1.1.0
- 1.0.4
- 1.0.3
- 1.0.2
- 1.0.1
- 1.0.0
- 0.12.44
- 0.12.43
- 0.12.42
- 0.12.41
- 0.12.40
- 0.12.39
- 0.12.38
- 0.12.37
- 0.12.36
- 0.12.35
- 0.12.34
- 0.12.33
- 0.12.32
- 0.12.31
- 0.12.30
- 0.12.29
- 0.12.28
- 0.12.27
- 0.12.26
- 0.12.25
- 0.12.24
- 0.12.23
- 0.12.22
- 0.12.21
- 0.12.20
- 0.12.19
- 0.12.18
- 0.12.17
- 0.12.16
- 0.12.15
- 0.12.14
- 0.12.13
- 0.12.12
- 0.12.11
- 0.12.10
- 0.12.9
- 0.12.8
- 0.12.7
- 0.12.6
- 0.12.5
- 0.12.4
- 0.12.3
- 0.12.2
- 0.12.1
- 0.12.0
- 0.11.6
- 0.11.5
- 0.11.4
- 0.11.3
- 0.11.2
- 0.11.1
- 0.11
- 0.10
- 0.9.1
- 0.9
- 0.8
- 0.7
- 0.6.1
- 0.6
- dev-renovate/major-root-composer
- dev-renovate/major-github-actions
- dev-get-array-result
- dev-test-failures
- dev-revert-array-result
- dev-more-updates
- dev-update-em-create
- dev-update-cache
- dev-update-dependencies
- dev-revert-56-fix/52-find-by-methods
This package is auto-updated.
Last update: 2024-12-02 16:51:37 UTC
README
This extension provides following features:
- DQL validation for parse errors, unknown entity classes and unknown persistent fields. QueryBuilder validation is also supported.
- Recognizes magic
findBy*
,findOneBy*
andcountBy*
methods on EntityRepository. - Validates entity fields in repository
findBy
,findBy*
,findOneBy
,findOneBy*
,count
andcountBy*
method calls. - Interprets
EntityRepository<MyEntity>
correctly in phpDocs for further type inference of methods called on the repository. - Provides correct return for
Doctrine\ORM\EntityManager::getRepository()
. - Provides correct return type for
Doctrine\ORM\EntityManager::find
,getReference
andgetPartialReference
whenFoo::class
entity class name is provided as the first argument - Adds missing
matching
method onDoctrine\Common\Collections\Collection
. This can be turned off by settingparameters.doctrine.allCollectionsSelectable
tofalse
. - Also supports Doctrine ODM.
- Analysis of discrepancies between entity column types and property field types. This can be relaxed with the
allowNullablePropertyForRequiredField: true
setting. - Provides return type for
Doctrine\ORM\Query::getResult
,getOneOrNullResult
,getSingleResult
,toIterable
andexecute
inHYDRATE_OBJECT
mode (see below).
Installation
To use this extension, require it in Composer:
composer require --dev phpstan/phpstan-doctrine
If 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.neon
If 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.neon
Configuration
If 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\BetterDocumentRepository
You 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.php
Example 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();
Query type inference
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<Acme\User> $query = $entityManager->createQuery('SELECT u.id, u.email, u.name FROM Acme\User u'); $query->getResult(); // array<array{id: int, email: string, name: string|null}> $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(); // array<Acme\User>
Queries 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
).
Query type inference of expressions
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
.
Supported methods
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<User> $query->getResult(Query::HYDRATE_OBJECT); // array<User>
The 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); // User
This 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.
Problematic approaches
Not every QueryBuilder can be statically analysed, here are few advices to maximize type inferring:
- Do not pass QueryBuilder to methods
- Do not use dynamic expressions in QueryBuilder methods (mainly in
select
/join
/from
/set
)
You can enable reporting of places where inferring is unavailable by:
parameters: doctrine: reportDynamicQueryBuilders: true
Custom types
If 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:
<?php public function getType(): string; public function getWritableToPropertyType(): Type; public function getWritableToDatabaseType(): Type;
- The
getType()
method simply returns the class name of the custom type. - The
getWritableToPropertyType()
method returns the PHPStan type that the custom type will write into the entity's property field. Basically it is the return type of the custom type'sconvertToPHPValue()
method. - The
getWritableToDatabaseType()
method returns the PHPStan type that can be written from the entity's property field into the custom type. Again, basically it's the allowed type for the custom type'sconvertToDatabaseValue()
's first argument.
Generally, at least for most of Doctrine's native types, these last two methods will return the same type, but it is not always the case. One example would be the datetime
type, which allows you to set any \DateTimeInterface
into to property field, but will always contain the \DateTime
type when loaded from the database.
Nullable types
Type descriptors don't have to deal with nullable types, as these are transparently added/removed from the descriptor's types as needed. Therefore you don't have to return the union type of your custom type and NullType
from the descriptor's methods, even if your custom type allows null
.
ReflectionDescriptor
If your custom type's convertToPHPValue()
and convertToDatabaseValue()
methods have proper typehints, you don't have to write your own descriptor for it. The PHPStan\Type\Doctrine\Descriptors\ReflectionDescriptor
can analyse the typehints and do the rest for you.
If parent of your type is one of the Doctrine's non-abstract ones, ReflectionDescriptor
will reuse its descriptor even for expression resolution (e.g. AVG(t.cost)
).
For example, if you extend Doctrine\DBAL\Types\DecimalType
, it will know that sqlite fetches that as float|int
and other drivers as numeric-string
.
If you extend only Doctrine\DBAL\Types\Type
, you should use custom descriptor and optionally implement even DoctrineTypeDriverAwareDescriptor
to provide driver-specific resolution.
Registering type descriptors
When you write a custom type descriptor, you have to let PHPStan know about it. Add something like this into your phpstan.neon
:
services: - class: MyCustomTypeDescriptor tags: [phpstan.doctrine.typeDescriptor] # in case you are using the ReflectionDescriptor - factory: PHPStan\Type\Doctrine\Descriptors\ReflectionDescriptor('MyApp\MyCustomTypeName') tags: [phpstan.doctrine.typeDescriptor]
Ensure types have descriptor
If you want to be sure you never forget descriptor for some custom type, you can enable:
parameters: doctrine: reportUnknownTypes: true
This causes failures when your entity uses custom type without descriptor:
#[Entity] abstract class Uuid7Entity { #[Id] #[Column(type: Uuid7Type::NAME)] // reported when descriptor for such type is missing private Uuid7 $hsCode;
Custom DQL functions
Any custom DQL function that implements Doctrine's TypedExpression
is understood by this extension and is inferred with the type used in its getReturnType()
method.
All other custom DQL functions are inferred as mixed
.
Please note that you cannot use native StringType
to cast (and infer) string results (see ORM issue).
use Doctrine\DBAL\Types\Type; use Doctrine\DBAL\Types\Types; use Doctrine\ORM\Query\AST\TypedExpression; use Doctrine\ORM\Query\AST\Functions\FunctionNode; use Doctrine\ORM\Query\Parser; use Doctrine\ORM\Query\SqlWalker; use Doctrine\ORM\Query\TokenType; class Floor extends FunctionNode implements TypedExpression { private AST\Node|string $arithmeticExpression; public function getSql(SqlWalker $sqlWalker): string { return 'FLOOR(' . $sqlWalker->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); } }
Literal strings
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: true