Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enum support in query type inference #348

Merged
merged 6 commits into from
Jul 13, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -11,3 +11,5 @@ phpstan.neon export-ignore
phpstan-baseline.neon export-ignore
phpstan-baseline-dbal-3.neon export-ignore
phpunit.xml export-ignore
stubs/runtime/Enum/UnitEnum.php export-ignore
stubs/runtime/Enum/BackedEnum.php export-ignore
5 changes: 1 addition & 4 deletions composer.json
Original file line number Diff line number Diff line change
@@ -39,10 +39,7 @@
"ext-mongo": "1.12",
"ext-mongodb": "1.6.16"
},
"sort-packages": true,
"allow-plugins": {
"composer/package-versions-deprecated": true
}
"sort-packages": true
},
"extra": {
"phpstan": {
4 changes: 4 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
@@ -17,6 +17,10 @@ parameters:

reportUnmatchedIgnoredErrors: false

bootstrapFiles:
- stubs/runtime/Enum/UnitEnum.php
- stubs/runtime/Enum/BackedEnum.php
Comment on lines +20 to +22
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This makes supporting PHP versions bellow 8.1 much easier

Specifically, this allows code such as these to pass analysis:

is_subclass_of($className, BackedEnum::class)
/** @return class-string<BackedEnum> */

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be nice to ignore these runtime stubs in .gitattributes :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, done 👍


ignoreErrors:
-
message: '~^Variable method call on Doctrine\\ORM\\QueryBuilder~'
81 changes: 55 additions & 26 deletions src/Type/Doctrine/Query/QueryResultTypeWalker.php
Original file line number Diff line number Diff line change
@@ -2,8 +2,10 @@

namespace PHPStan\Type\Doctrine\Query;

use BackedEnum;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Doctrine\ORM\Query;
use Doctrine\ORM\Query\AST;
use Doctrine\ORM\Query\AST\TypedExpression;
@@ -15,6 +17,7 @@
use PHPStan\Type\Constant\ConstantFloatType;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\ConstantTypeHelper;
use PHPStan\Type\Doctrine\DescriptorNotRegisteredException;
use PHPStan\Type\Doctrine\DescriptorRegistry;
use PHPStan\Type\FloatType;
@@ -31,6 +34,7 @@
use PHPStan\Type\TypeTraverser;
use PHPStan\Type\TypeUtils;
use PHPStan\Type\UnionType;
use function array_map;
use function assert;
use function class_exists;
use function count;
@@ -42,6 +46,7 @@
use function is_numeric;
use function is_object;
use function is_string;
use function is_subclass_of;
use function serialize;
use function sprintf;
use function strtolower;
@@ -231,15 +236,13 @@ public function walkPathExpression($pathExpr)

switch ($pathExpr->type) {
case AST\PathExpression::TYPE_STATE_FIELD:
$typeName = $class->getTypeOfField($fieldName);

assert(is_string($typeName));
[$typeName, $enumType] = $this->getTypeOfField($class, $fieldName);

$nullable = $this->isQueryComponentNullable($dqlAlias)
|| $class->isNullable($fieldName)
|| $this->hasAggregateWithoutGroupBy();

$fieldType = $this->resolveDatabaseInternalType($typeName, $nullable);
$fieldType = $this->resolveDatabaseInternalType($typeName, $enumType, $nullable);

return $this->marshalType($fieldType);

@@ -273,14 +276,12 @@ public function walkPathExpression($pathExpr)
}

$targetFieldName = $identifierFieldNames[0];
$typeName = $targetClass->getTypeOfField($targetFieldName);

assert(is_string($typeName));
[$typeName, $enumType] = $this->getTypeOfField($targetClass, $targetFieldName);

$nullable = (bool) ($joinColumn['nullable'] ?? true)
|| $this->hasAggregateWithoutGroupBy();

$fieldType = $this->resolveDatabaseInternalType($typeName, $nullable);
$fieldType = $this->resolveDatabaseInternalType($typeName, $enumType, $nullable);

return $this->marshalType($fieldType);

@@ -530,16 +531,13 @@ public function walkFunction($function)
$targetFieldName = $function->fieldMapping;
}

$typeName = $targetClass->getTypeOfField($targetFieldName);
if ($typeName === null) {
return $this->marshalType(new MixedType());
}

$fieldMapping = $targetClass->fieldMappings[$targetFieldName] ?? null;
if ($fieldMapping === null) {
return $this->marshalType(new MixedType());
}

[$typeName, $enumType] = $this->getTypeOfField($targetClass, $targetFieldName);

$joinColumn = null;

foreach ($assoc['joinColumns'] as $item) {
@@ -556,7 +554,7 @@ public function walkFunction($function)
$nullable = (bool) ($joinColumn['nullable'] ?? true)
|| $this->hasAggregateWithoutGroupBy();

$fieldType = $this->resolveDatabaseInternalType($typeName, $nullable);
$fieldType = $this->resolveDatabaseInternalType($typeName, $enumType, $nullable);

return $this->marshalType($fieldType);

@@ -783,15 +781,13 @@ public function walkSelectExpression($selectExpression)
$qComp = $this->queryComponents[$dqlAlias];
$class = $qComp['metadata'];

$typeName = $class->getTypeOfField($fieldName);

assert(is_string($typeName));
[$typeName, $enumType] = $this->getTypeOfField($class, $fieldName);

$nullable = $this->isQueryComponentNullable($dqlAlias)
|| $class->isNullable($fieldName)
|| $this->hasAggregateWithoutGroupBy();

$type = $this->resolveDoctrineType($typeName, $nullable);
$type = $this->resolveDoctrineType($typeName, $enumType, $nullable);

$this->typeBuilder->addScalar($resultAlias, $type);

@@ -1295,14 +1291,37 @@ private function isQueryComponentNullable(string $dqlAlias): bool
return $this->nullableQueryComponents[$dqlAlias] ?? false;
}

private function resolveDoctrineType(string $typeName, bool $nullable = false): Type
/** @return array{string, ?class-string<BackedEnum>} Doctrine type name and enum type of field */
private function getTypeOfField(ClassMetadataInfo $class, string $fieldName): array
{
try {
$type = $this->descriptorRegistry
->get($typeName)
->getWritableToPropertyType();
} catch (DescriptorNotRegisteredException $e) {
$type = new MixedType();
assert(isset($class->fieldMappings[$fieldName]));

/** @var array{type: string, enumType?: ?string} $metadata */
$metadata = $class->fieldMappings[$fieldName];

$type = $metadata['type'];
$enumType = $metadata['enumType'] ?? null;

if (!is_string($enumType) || !class_exists($enumType) || !is_subclass_of($enumType, BackedEnum::class)) {
$enumType = null;
}

return [$type, $enumType];
}

/** @param ?class-string<BackedEnum> $enumType */
private function resolveDoctrineType(string $typeName, ?string $enumType = null, bool $nullable = false): Type
{
if ($enumType !== null) {
$type = new ObjectType($enumType);
} else {
try {
$type = $this->descriptorRegistry
->get($typeName)
->getWritableToPropertyType();
} catch (DescriptorNotRegisteredException $e) {
$type = new MixedType();
}
}

if ($nullable) {
@@ -1312,7 +1331,8 @@ private function resolveDoctrineType(string $typeName, bool $nullable = false):
return $type;
}

private function resolveDatabaseInternalType(string $typeName, bool $nullable = false): Type
/** @param ?class-string<BackedEnum> $enumType */
private function resolveDatabaseInternalType(string $typeName, ?string $enumType = null, bool $nullable = false): Type
{
try {
$type = $this->descriptorRegistry
@@ -1322,6 +1342,15 @@ private function resolveDatabaseInternalType(string $typeName, bool $nullable =
$type = new MixedType();
}

if ($enumType !== null) {
$enumTypes = array_map(static function ($enumType) {
return ConstantTypeHelper::getTypeFromValue($enumType->value);
}, $enumType::cases());
$enumType = TypeCombinator::union(...$enumTypes);
$enumType = TypeCombinator::union($enumType, $enumType->toString());
$type = TypeCombinator::intersect($enumType, $type);
}

if ($nullable) {
$type = TypeCombinator::addNull($type);
}
22 changes: 22 additions & 0 deletions stubs/runtime/Enum/BackedEnum.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

if (\PHP_VERSION_ID < 80100) {
if (interface_exists('BackedEnum', false)) {
return;
}

interface BackedEnum extends UnitEnum
Comment on lines +3 to +8
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

{
/**
* @param int|string $value
* @return static
*/
public static function from($value);

/**
* @param int|string $value
* @return ?static
*/
public static function tryFrom($value);
}
}
15 changes: 15 additions & 0 deletions stubs/runtime/Enum/UnitEnum.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

if (\PHP_VERSION_ID < 80100) {
if (interface_exists('UnitEnum', false)) {
return;
}

interface UnitEnum
{
/**
* @return static[]
*/
public static function cases(): array;
}
}
Loading