Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Enum support in query type inference #348

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

Merged
ondrejmirtes merged 6 commits into phpstan:1.3.x from arnaud-lb:enums
Jul 13, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 3 additions & 1 deletion composer.json
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"doctrine/persistence": "^1.3.8 || ^2.2.1",
"nesbot/carbon": "^2.49",
"nikic/php-parser": "^4.13.2",
"ocramius/package-versions": "*",
Copy link
Contributor Author

@arnaud-lb arnaud-lb Jul 6, 2022

Choose a reason for hiding this comment

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

We need this to skip some test when running Doctrine 2.11

Copy link
Member

@ondrejmirtes ondrejmirtes Jul 10, 2022

Choose a reason for hiding this comment

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

There's now a native Composer feature for this so we don't need a package I think? https://getcomposer.org/doc/07-runtime.md

Copy link
Contributor Author

@arnaud-lb arnaud-lb Jul 10, 2022

Choose a reason for hiding this comment

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

Great, didn't know that. I've updated the PR to use this instead.

Copy link
Member

@ondrejmirtes ondrejmirtes Jul 10, 2022

Choose a reason for hiding this comment

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

We can remove this from composer.json now? :)

Copy link
Contributor Author

@arnaud-lb arnaud-lb Jul 10, 2022

Choose a reason for hiding this comment

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

Ah, gone too fast and forgot this. I've removed it now

"php-parallel-lint/php-parallel-lint": "^1.2",
"phpstan/phpstan-phpunit": "^1.0",
"phpstan/phpstan-strict-rules": "^1.0",
Expand All @@ -41,7 +42,8 @@
},
"sort-packages": true,
"allow-plugins": {
"composer/package-versions-deprecated": true
"composer/package-versions-deprecated": true,
"ocramius/package-versions": true
}
},
"extra": {
Expand Down
4 changes: 4 additions & 0 deletions phpstan.neon
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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

@arnaud-lb arnaud-lb Jul 6, 2022

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

@ondrejmirtes ondrejmirtes Jul 10, 2022

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

@arnaud-lb arnaud-lb Jul 10, 2022

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~'
Expand Down
81 changes: 55 additions & 26 deletions src/Type/Doctrine/Query/QueryResultTypeWalker.php
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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) {
Expand All @@ -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);

Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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) {
Expand All @@ -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
Expand All @@ -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);
}
Expand Down
22 changes: 22 additions & 0 deletions stubs/runtime/Enum/BackedEnum.php
View file Open in desktop
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

@arnaud-lb arnaud-lb Jul 6, 2022

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
View file Open in desktop
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

AltStyle によって変換されたページ (->オリジナル) /