From ebe65cc46f06237ea2a1f5ccc2a4f867636fc23b Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Mon, 26 Dec 2022 21:06:02 +0100 Subject: [PATCH 01/11] Improve QueryResultDynamicReturnTypeExtension --- .../QueryResultDynamicReturnTypeExtension.php | 168 +++++++- .../Doctrine/data/QueryResult/queryResult.php | 400 +++++++++++++++++- 2 files changed, 537 insertions(+), 31 deletions(-) diff --git a/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php b/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php index 20e23831..a46f96be 100644 --- a/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php +++ b/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php @@ -10,14 +10,21 @@ use PHPStan\ShouldNotHappenException; use PHPStan\Type\Accessory\AccessoryArrayListType; use PHPStan\Type\ArrayType; +use PHPStan\Type\Constant\ConstantArrayType; use PHPStan\Type\Constant\ConstantIntegerType; +use PHPStan\Type\Doctrine\ObjectMetadataResolver; use PHPStan\Type\DynamicMethodReturnTypeExtension; use PHPStan\Type\IntegerType; use PHPStan\Type\IterableType; +use PHPStan\Type\MixedType; use PHPStan\Type\NullType; +use PHPStan\Type\ObjectWithoutClassType; use PHPStan\Type\Type; use PHPStan\Type\TypeCombinator; +use PHPStan\Type\TypeTraverser; +use PHPStan\Type\TypeWithClassName; use PHPStan\Type\VoidType; +use function count; final class QueryResultDynamicReturnTypeExtension implements DynamicMethodReturnTypeExtension { @@ -32,6 +39,23 @@ final class QueryResultDynamicReturnTypeExtension implements DynamicMethodReturn 'getSingleResult' => 0, ]; + private const METHOD_HYDRATION_MODE = [ + 'getArrayResult' => AbstractQuery::HYDRATE_ARRAY, + 'getScalarResult' => AbstractQuery::HYDRATE_SCALAR, + 'getSingleColumnResult' => AbstractQuery::HYDRATE_SCALAR_COLUMN, + 'getSingleScalarResult' => AbstractQuery::HYDRATE_SINGLE_SCALAR, + ]; + + /** @var ObjectMetadataResolver */ + private $objectMetadataResolver; + + public function __construct( + ObjectMetadataResolver $objectMetadataResolver + ) + { + $this->objectMetadataResolver = $objectMetadataResolver; + } + public function getClass(): string { return AbstractQuery::class; @@ -39,7 +63,8 @@ public function getClass(): string public function isMethodSupported(MethodReflection $methodReflection): bool { - return isset(self::METHOD_HYDRATION_MODE_ARG[$methodReflection->getName()]); + return isset(self::METHOD_HYDRATION_MODE_ARG[$methodReflection->getName()]) + || isset(self::METHOD_HYDRATION_MODE[$methodReflection->getName()]); } public function getTypeFromMethodCall( @@ -50,21 +75,23 @@ public function getTypeFromMethodCall( { $methodName = $methodReflection->getName(); - if (!isset(self::METHOD_HYDRATION_MODE_ARG[$methodName])) { - throw new ShouldNotHappenException(); - } - - $argIndex = self::METHOD_HYDRATION_MODE_ARG[$methodName]; - $args = $methodCall->getArgs(); + if (isset(self::METHOD_HYDRATION_MODE[$methodName])) { + $hydrationMode = new ConstantIntegerType(self::METHOD_HYDRATION_MODE[$methodName]); + } elseif (isset(self::METHOD_HYDRATION_MODE_ARG[$methodName])) { + $argIndex = self::METHOD_HYDRATION_MODE_ARG[$methodName]; + $args = $methodCall->getArgs(); - if (isset($args[$argIndex])) { - $hydrationMode = $scope->getType($args[$argIndex]->value); + if (isset($args[$argIndex])) { + $hydrationMode = $scope->getType($args[$argIndex]->value); + } else { + $parametersAcceptor = ParametersAcceptorSelector::selectSingle( + $methodReflection->getVariants() + ); + $parameter = $parametersAcceptor->getParameters()[$argIndex]; + $hydrationMode = $parameter->getDefaultValue() ?? new NullType(); + } } else { - $parametersAcceptor = ParametersAcceptorSelector::selectSingle( - $methodReflection->getVariants() - ); - $parameter = $parametersAcceptor->getParameters()[$argIndex]; - $hydrationMode = $parameter->getDefaultValue() ?? new NullType(); + throw new ShouldNotHappenException(); } $queryType = $scope->getType($methodCall->var); @@ -98,12 +125,34 @@ private function getMethodReturnTypeForHydrationMode( return $this->originalReturnType($methodReflection); } - if (!$this->isObjectHydrationMode($hydrationMode)) { - // We support only HYDRATE_OBJECT. For other hydration modes, we - // return the declared return type of the method. + if (!$hydrationMode instanceof ConstantIntegerType) { return $this->originalReturnType($methodReflection); } + $singleResult = false; + switch ($hydrationMode->getValue()) { + case AbstractQuery::HYDRATE_OBJECT: + break; + case AbstractQuery::HYDRATE_ARRAY: + $queryResultType = $this->getArrayHydratedReturnType($queryResultType); + break; + case AbstractQuery::HYDRATE_SCALAR: + $queryResultType = $this->getScalarHydratedReturnType($queryResultType); + break; + case AbstractQuery::HYDRATE_SINGLE_SCALAR: + $singleResult = true; + $queryResultType = $this->getSingleScalarHydratedReturnType($queryResultType); + break; + case AbstractQuery::HYDRATE_SIMPLEOBJECT: + $queryResultType = $this->getSimpleObjectHydratedReturnType($queryResultType); + break; + case AbstractQuery::HYDRATE_SCALAR_COLUMN: + $queryResultType = $this->getScalarColumnHydratedReturnType($queryResultType); + break; + default: + return $this->originalReturnType($methodReflection); + } + switch ($methodReflection->getName()) { case 'getSingleResult': return $queryResultType; @@ -115,6 +164,10 @@ private function getMethodReturnTypeForHydrationMode( $queryResultType ); default: + if ($singleResult) { + return $queryResultType; + } + if ($queryKeyType->isNull()->yes()) { return AccessoryArrayListType::intersectWith(new ArrayType( new IntegerType(), @@ -128,13 +181,86 @@ private function getMethodReturnTypeForHydrationMode( } } - private function isObjectHydrationMode(Type $type): bool + private function getArrayHydratedReturnType(Type $queryResultType): Type + { + $objectManager = $this->objectMetadataResolver->getObjectManager(); + + return TypeTraverser::map( + $queryResultType, + static function (Type $type, callable $traverse) use ($objectManager): Type { + $isObject = (new ObjectWithoutClassType())->isSuperTypeOf($type); + if ($isObject->no()) { + return $traverse($type); + } + if ( + $isObject->maybe() + || !$type instanceof TypeWithClassName + || $objectManager === null + ) { + return new MixedType(); + } + + return $objectManager->getMetadataFactory()->hasMetadataFor($type->getClassName()) + ? new ArrayType(new MixedType(), new MixedType()) + : $traverse($type); + } + ); + } + + private function getScalarHydratedReturnType(Type $queryResultType): Type + { + if (!$queryResultType instanceof ArrayType) { + return new ArrayType(new MixedType(), new MixedType()); + } + + $itemType = $queryResultType->getItemType(); + $hasNoObject = (new ObjectWithoutClassType())->isSuperTypeOf($itemType)->no(); + $hasNoArray = $itemType->isArray()->no(); + + if ($hasNoArray && $hasNoObject) { + return $queryResultType; + } + + return new ArrayType(new MixedType(), new MixedType()); + } + + private function getSimpleObjectHydratedReturnType(Type $queryResultType): Type { - if (!$type instanceof ConstantIntegerType) { - return false; + if ((new ObjectWithoutClassType())->isSuperTypeOf($queryResultType)->yes()) { + return $queryResultType; + } + + return new MixedType(); + } + + private function getSingleScalarHydratedReturnType(Type $queryResultType): Type + { + $queryResultType = $this->getScalarHydratedReturnType($queryResultType); + if (!$queryResultType instanceof ConstantArrayType) { + return new MixedType(); + } + + $values = $queryResultType->getValueTypes(); + if (count($values) !== 1) { + return new MixedType(); + } + + return $queryResultType->getFirstIterableValueType(); + } + + private function getScalarColumnHydratedReturnType(Type $queryResultType): Type + { + $queryResultType = $this->getScalarHydratedReturnType($queryResultType); + if (!$queryResultType instanceof ConstantArrayType) { + return new MixedType(); + } + + $values = $queryResultType->getValueTypes(); + if (count($values) !== 1) { + return new MixedType(); } - return $type->getValue() === AbstractQuery::HYDRATE_OBJECT; + return $queryResultType->getFirstIterableValueType(); } private function originalReturnType(MethodReflection $methodReflection): Type diff --git a/tests/Type/Doctrine/data/QueryResult/queryResult.php b/tests/Type/Doctrine/data/QueryResult/queryResult.php index 02469e46..0a67f4f0 100644 --- a/tests/Type/Doctrine/data/QueryResult/queryResult.php +++ b/tests/Type/Doctrine/data/QueryResult/queryResult.php @@ -144,11 +144,11 @@ public function testReturnTypeOfQueryMethodsWithExplicitObjectHydrationMode(Enti } /** - * Test that we properly infer the return type of Query methods with explicit hydration mode that is not HYDRATE_OBJECT + * Test that we properly infer the return type of Query methods with explicit hydration mode of HYDRATE_ARRAY * - * We are never able to infer the return type here + * We can infer the return type by changing every object by an array */ - public function testReturnTypeOfQueryMethodsWithExplicitNonObjectHydrationMode(EntityManagerInterface $em): void + public function testReturnTypeOfQueryMethodsWithExplicitArrayHydrationMode(EntityManagerInterface $em): void { $query = $em->createQuery(' SELECT m @@ -156,35 +156,415 @@ public function testReturnTypeOfQueryMethodsWithExplicitNonObjectHydrationMode(E '); assertType( - 'mixed', + 'list', $query->getResult(AbstractQuery::HYDRATE_ARRAY) ); assertType( - 'iterable', + 'list', + $query->getArrayResult() + ); + assertType( + 'iterable', $query->toIterable([], AbstractQuery::HYDRATE_ARRAY) ); assertType( - 'mixed', + 'list', $query->execute(null, AbstractQuery::HYDRATE_ARRAY) ); assertType( - 'mixed', + 'list', $query->executeIgnoreQueryCache(null, AbstractQuery::HYDRATE_ARRAY) ); assertType( - 'mixed', + 'list', $query->executeUsingQueryCache(null, AbstractQuery::HYDRATE_ARRAY) ); assertType( - 'mixed', + 'array', $query->getSingleResult(AbstractQuery::HYDRATE_ARRAY) ); assertType( - 'mixed', + 'array|null', + $query->getOneOrNullResult(AbstractQuery::HYDRATE_ARRAY) + ); + + $query = $em->createQuery(' + SELECT m.intColumn, m.stringNullColumn, m.datetimeColumn + FROM QueryResult\Entities\Many m + '); + + assertType( + 'list', + $query->getResult(AbstractQuery::HYDRATE_ARRAY) + ); + assertType( + 'list', + $query->getArrayResult() + ); + assertType( + 'list', + $query->execute(null, AbstractQuery::HYDRATE_ARRAY) + ); + assertType( + 'list', + $query->executeIgnoreQueryCache(null, AbstractQuery::HYDRATE_ARRAY) + ); + assertType( + 'list', + $query->executeUsingQueryCache(null, AbstractQuery::HYDRATE_ARRAY) + ); + assertType( + 'array{intColumn: int, stringNullColumn: string|null, datetimeColumn: DateTime}', + $query->getSingleResult(AbstractQuery::HYDRATE_ARRAY) + ); + assertType( + 'array{intColumn: int, stringNullColumn: string|null, datetimeColumn: DateTime}|null', $query->getOneOrNullResult(AbstractQuery::HYDRATE_ARRAY) ); } + /** + * Test that we properly infer the return type of Query methods with explicit hydration mode of HYDRATE_SCALAR + */ + public function testReturnTypeOfQueryMethodsWithExplicitScalarHydrationMode(EntityManagerInterface $em): void + { + $query = $em->createQuery(' + SELECT m + FROM QueryResult\Entities\Many m + '); + + assertType( + 'list', + $query->getResult(AbstractQuery::HYDRATE_SCALAR) + ); + assertType( + 'list', + $query->getScalarResult() + ); + assertType( + 'iterable', + $query->toIterable([], AbstractQuery::HYDRATE_SCALAR) + ); + assertType( + 'list', + $query->execute(null, AbstractQuery::HYDRATE_SCALAR) + ); + assertType( + 'list', + $query->executeIgnoreQueryCache(null, AbstractQuery::HYDRATE_SCALAR) + ); + assertType( + 'list', + $query->executeUsingQueryCache(null, AbstractQuery::HYDRATE_SCALAR) + ); + assertType( + 'array', + $query->getSingleResult(AbstractQuery::HYDRATE_SCALAR) + ); + assertType( + 'array|null', + $query->getOneOrNullResult(AbstractQuery::HYDRATE_SCALAR) + ); + + $query = $em->createQuery(' + SELECT m.intColumn, m.stringNullColumn + FROM QueryResult\Entities\Many m + '); + + assertType( + 'list', + $query->getResult(AbstractQuery::HYDRATE_SCALAR) + ); + assertType( + 'list', + $query->getScalarResult() + ); + assertType( + 'list', + $query->execute(null, AbstractQuery::HYDRATE_SCALAR) + ); + assertType( + 'list', + $query->executeIgnoreQueryCache(null, AbstractQuery::HYDRATE_SCALAR) + ); + assertType( + 'list', + $query->executeUsingQueryCache(null, AbstractQuery::HYDRATE_SCALAR) + ); + assertType( + 'array{intColumn: int, stringNullColumn: string|null}', + $query->getSingleResult(AbstractQuery::HYDRATE_SCALAR) + ); + assertType( + 'array{intColumn: int, stringNullColumn: string|null}|null', + $query->getOneOrNullResult(AbstractQuery::HYDRATE_SCALAR) + ); + } + + /** + * Test that we properly infer the return type of Query methods with explicit hydration mode of HYDRATE_SCALAR + */ + public function testReturnTypeOfQueryMethodsWithExplicitSingleScalarHydrationMode(EntityManagerInterface $em): void + { + $query = $em->createQuery(' + SELECT m + FROM QueryResult\Entities\Many m + '); + + assertType( + 'mixed', + $query->getResult(AbstractQuery::HYDRATE_SINGLE_SCALAR) + ); + assertType( + 'mixed', + $query->getSingleScalarResult() + ); + assertType( + 'iterable', + $query->toIterable([], AbstractQuery::HYDRATE_SINGLE_SCALAR) + ); + assertType( + 'mixed', + $query->execute(null, AbstractQuery::HYDRATE_SINGLE_SCALAR) + ); + assertType( + 'mixed', + $query->executeIgnoreQueryCache(null, AbstractQuery::HYDRATE_SINGLE_SCALAR) + ); + assertType( + 'mixed', + $query->executeUsingQueryCache(null, AbstractQuery::HYDRATE_SINGLE_SCALAR) + ); + assertType( + 'mixed', + $query->getSingleResult(AbstractQuery::HYDRATE_SINGLE_SCALAR) + ); + assertType( + 'mixed', + $query->getOneOrNullResult(AbstractQuery::HYDRATE_SINGLE_SCALAR) + ); + + $query = $em->createQuery(' + SELECT m.intColumn + FROM QueryResult\Entities\Many m + '); + + assertType( + 'int', + $query->getResult(AbstractQuery::HYDRATE_SINGLE_SCALAR) + ); + assertType( + 'int', + $query->getSingleScalarResult() + ); + assertType( + 'int', + $query->execute(null, AbstractQuery::HYDRATE_SINGLE_SCALAR) + ); + assertType( + 'int', + $query->executeIgnoreQueryCache(null, AbstractQuery::HYDRATE_SINGLE_SCALAR) + ); + assertType( + 'int', + $query->executeUsingQueryCache(null, AbstractQuery::HYDRATE_SINGLE_SCALAR) + ); + assertType( + 'int', + $query->getSingleResult(AbstractQuery::HYDRATE_SINGLE_SCALAR) + ); + assertType( + 'int|null', + $query->getOneOrNullResult(AbstractQuery::HYDRATE_SINGLE_SCALAR) + ); + + $query = $em->createQuery(' + SELECT COUNT(m.id) + FROM QueryResult\Entities\Many m + '); + + assertType( + 'int<0, max>|numeric-string', + $query->getResult(AbstractQuery::HYDRATE_SINGLE_SCALAR) + ); + assertType( + 'int<0, max>|numeric-string', + $query->getSingleScalarResult() + ); + assertType( + 'int<0, max>|numeric-string', + $query->execute(null, AbstractQuery::HYDRATE_SINGLE_SCALAR) + ); + assertType( + 'int<0, max>|numeric-string', + $query->executeIgnoreQueryCache(null, AbstractQuery::HYDRATE_SINGLE_SCALAR) + ); + assertType( + 'int<0, max>|numeric-string', + $query->executeUsingQueryCache(null, AbstractQuery::HYDRATE_SINGLE_SCALAR) + ); + assertType( + 'int<0, max>|numeric-string', + $query->getSingleResult(AbstractQuery::HYDRATE_SINGLE_SCALAR) + ); + assertType( + 'int<0, max>|numeric-string|null', + $query->getOneOrNullResult(AbstractQuery::HYDRATE_SINGLE_SCALAR) + ); + } + + /** + * Test that we properly infer the return type of Query methods with explicit hydration mode of HYDRATE_SIMPLEOBJECT + * + * We are never able to infer the return type here + */ + public function testReturnTypeOfQueryMethodsWithExplicitSimpleObjectHydrationMode(EntityManagerInterface $em): void + { + $query = $em->createQuery(' + SELECT m + FROM QueryResult\Entities\Many m + '); + + assertType( + 'list', + $query->getResult(AbstractQuery::HYDRATE_SIMPLEOBJECT) + ); + assertType( + 'iterable', + $query->toIterable([], AbstractQuery::HYDRATE_SIMPLEOBJECT) + ); + assertType( + 'list', + $query->execute(null, AbstractQuery::HYDRATE_SIMPLEOBJECT) + ); + assertType( + 'list', + $query->executeIgnoreQueryCache(null, AbstractQuery::HYDRATE_SIMPLEOBJECT) + ); + assertType( + 'list', + $query->executeUsingQueryCache(null, AbstractQuery::HYDRATE_SIMPLEOBJECT) + ); + assertType( + 'QueryResult\Entities\Many', + $query->getSingleResult(AbstractQuery::HYDRATE_SIMPLEOBJECT) + ); + assertType( + 'QueryResult\Entities\Many|null', + $query->getOneOrNullResult(AbstractQuery::HYDRATE_SIMPLEOBJECT) + ); + + $query = $em->createQuery(' + SELECT m.intColumn, m.stringNullColumn + FROM QueryResult\Entities\Many m + '); + + assertType( + 'list', + $query->getResult(AbstractQuery::HYDRATE_SIMPLEOBJECT) + ); + assertType( + 'list', + $query->execute(null, AbstractQuery::HYDRATE_SIMPLEOBJECT) + ); + assertType( + 'list', + $query->executeIgnoreQueryCache(null, AbstractQuery::HYDRATE_SIMPLEOBJECT) + ); + assertType( + 'list', + $query->executeUsingQueryCache(null, AbstractQuery::HYDRATE_SIMPLEOBJECT) + ); + assertType( + 'mixed', + $query->getSingleResult(AbstractQuery::HYDRATE_SIMPLEOBJECT) + ); + assertType( + 'mixed', + $query->getOneOrNullResult(AbstractQuery::HYDRATE_SIMPLEOBJECT) + ); + } + + /** + * Test that we properly infer the return type of Query methods with explicit hydration mode of HYDRATE_SCALAR_COLUMN + * + * We are never able to infer the return type here + */ + public function testReturnTypeOfQueryMethodsWithExplicitScalarColumnHydrationMode(EntityManagerInterface $em): void + { + $query = $em->createQuery(' + SELECT m + FROM QueryResult\Entities\Many m + '); + + assertType( + 'list', + $query->getResult(AbstractQuery::HYDRATE_SCALAR_COLUMN) + ); + assertType( + 'list', + $query->getSingleColumnResult() + ); + assertType( + 'iterable', + $query->toIterable([], AbstractQuery::HYDRATE_SCALAR_COLUMN) + ); + assertType( + 'list', + $query->execute(null, AbstractQuery::HYDRATE_SCALAR_COLUMN) + ); + assertType( + 'list', + $query->executeIgnoreQueryCache(null, AbstractQuery::HYDRATE_SCALAR_COLUMN) + ); + assertType( + 'list', + $query->executeUsingQueryCache(null, AbstractQuery::HYDRATE_SCALAR_COLUMN) + ); + assertType( + 'mixed', + $query->getSingleResult(AbstractQuery::HYDRATE_SCALAR_COLUMN) + ); + assertType( + 'mixed', + $query->getOneOrNullResult(AbstractQuery::HYDRATE_SCALAR_COLUMN) + ); + + $query = $em->createQuery(' + SELECT m.intColumn + FROM QueryResult\Entities\Many m + '); + + assertType( + 'list', + $query->getResult(AbstractQuery::HYDRATE_SCALAR_COLUMN) + ); + assertType( + 'list', + $query->getSingleColumnResult() + ); + assertType( + 'list', + $query->execute(null, AbstractQuery::HYDRATE_SCALAR_COLUMN) + ); + assertType( + 'list', + $query->executeIgnoreQueryCache(null, AbstractQuery::HYDRATE_SCALAR_COLUMN) + ); + assertType( + 'list', + $query->executeUsingQueryCache(null, AbstractQuery::HYDRATE_SCALAR_COLUMN) + ); + assertType( + 'int', + $query->getSingleResult(AbstractQuery::HYDRATE_SCALAR_COLUMN) + ); + assertType( + 'int|null', + $query->getOneOrNullResult(AbstractQuery::HYDRATE_SCALAR_COLUMN) + ); + } + /** * Test that we properly infer the return type of Query methods with explicit hydration mode that is not a constant value * From 26674b840b0bf8424531a54b9446042255853b0c Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Sat, 25 Feb 2023 16:22:01 +0100 Subject: [PATCH 02/11] Solve phpstan deprecation --- .../QueryResultDynamicReturnTypeExtension.php | 48 ++++++++++++------- 1 file changed, 30 insertions(+), 18 deletions(-) diff --git a/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php b/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php index a46f96be..e7357b35 100644 --- a/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php +++ b/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php @@ -10,7 +10,6 @@ use PHPStan\ShouldNotHappenException; use PHPStan\Type\Accessory\AccessoryArrayListType; use PHPStan\Type\ArrayType; -use PHPStan\Type\Constant\ConstantArrayType; use PHPStan\Type\Constant\ConstantIntegerType; use PHPStan\Type\Doctrine\ObjectMetadataResolver; use PHPStan\Type\DynamicMethodReturnTypeExtension; @@ -209,19 +208,22 @@ static function (Type $type, callable $traverse) use ($objectManager): Type { private function getScalarHydratedReturnType(Type $queryResultType): Type { - if (!$queryResultType instanceof ArrayType) { + if (!$queryResultType->isArray()->yes()) { return new ArrayType(new MixedType(), new MixedType()); } - $itemType = $queryResultType->getItemType(); - $hasNoObject = (new ObjectWithoutClassType())->isSuperTypeOf($itemType)->no(); - $hasNoArray = $itemType->isArray()->no(); + foreach ($queryResultType->getArrays() as $arrayType) { + $itemType = $arrayType->getItemType(); - if ($hasNoArray && $hasNoObject) { - return $queryResultType; + if ( + !(new ObjectWithoutClassType())->isSuperTypeOf($itemType)->no() + || !$itemType->isArray()->no() + ) { + return new ArrayType(new MixedType(), new MixedType()); + } } - return new ArrayType(new MixedType(), new MixedType()); + return $queryResultType; } private function getSimpleObjectHydratedReturnType(Type $queryResultType): Type @@ -236,31 +238,41 @@ private function getSimpleObjectHydratedReturnType(Type $queryResultType): Type private function getSingleScalarHydratedReturnType(Type $queryResultType): Type { $queryResultType = $this->getScalarHydratedReturnType($queryResultType); - if (!$queryResultType instanceof ConstantArrayType) { + if (!$queryResultType->isConstantArray()->yes()) { return new MixedType(); } - $values = $queryResultType->getValueTypes(); - if (count($values) !== 1) { - return new MixedType(); + $types = []; + foreach ($queryResultType->getConstantArrays() as $constantArrayType) { + $values = $constantArrayType->getValueTypes(); + if (count($values) !== 1) { + return new MixedType(); + } + + $types[] = $constantArrayType->getFirstIterableValueType(); } - return $queryResultType->getFirstIterableValueType(); + return TypeCombinator::union(...$types); } private function getScalarColumnHydratedReturnType(Type $queryResultType): Type { $queryResultType = $this->getScalarHydratedReturnType($queryResultType); - if (!$queryResultType instanceof ConstantArrayType) { + if (!$queryResultType->isConstantArray()->yes()) { return new MixedType(); } - $values = $queryResultType->getValueTypes(); - if (count($values) !== 1) { - return new MixedType(); + $types = []; + foreach ($queryResultType->getConstantArrays() as $constantArrayType) { + $values = $constantArrayType->getValueTypes(); + if (count($values) !== 1) { + return new MixedType(); + } + + $types[] = $constantArrayType->getFirstIterableValueType(); } - return $queryResultType->getFirstIterableValueType(); + return TypeCombinator::union(...$types); } private function originalReturnType(MethodReflection $methodReflection): Type From b62df47561bb2fa5ebcd71e9ea5dce7785cdfc22 Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Wed, 5 Apr 2023 12:14:27 +0200 Subject: [PATCH 03/11] Avoid false positive about array result --- .../QueryResultDynamicReturnTypeExtension.php | 11 ++++++++--- .../Doctrine/data/QueryResult/queryResult.php | 16 ++++++++-------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php b/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php index e7357b35..7d047768 100644 --- a/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php +++ b/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php @@ -199,9 +199,14 @@ static function (Type $type, callable $traverse) use ($objectManager): Type { return new MixedType(); } - return $objectManager->getMetadataFactory()->hasMetadataFor($type->getClassName()) - ? new ArrayType(new MixedType(), new MixedType()) - : $traverse($type); + if (!$objectManager->getMetadataFactory()->hasMetadataFor($type->getClassName())) { + return $traverse($type); + } + + // We could return `new ArrayTyp(new MixedType(), new MixedType())` + // but the lack of precision in the array keys/values would give false positive + // @see https://github.com/phpstan/phpstan-doctrine/pull/412#issuecomment-1497092934 + return new MixedType(); } ); } diff --git a/tests/Type/Doctrine/data/QueryResult/queryResult.php b/tests/Type/Doctrine/data/QueryResult/queryResult.php index 0a67f4f0..272744df 100644 --- a/tests/Type/Doctrine/data/QueryResult/queryResult.php +++ b/tests/Type/Doctrine/data/QueryResult/queryResult.php @@ -156,35 +156,35 @@ public function testReturnTypeOfQueryMethodsWithExplicitArrayHydrationMode(Entit '); assertType( - 'list', + 'list', $query->getResult(AbstractQuery::HYDRATE_ARRAY) ); assertType( - 'list', + 'list', $query->getArrayResult() ); assertType( - 'iterable', + 'iterable', $query->toIterable([], AbstractQuery::HYDRATE_ARRAY) ); assertType( - 'list', + 'list', $query->execute(null, AbstractQuery::HYDRATE_ARRAY) ); assertType( - 'list', + 'list', $query->executeIgnoreQueryCache(null, AbstractQuery::HYDRATE_ARRAY) ); assertType( - 'list', + 'list', $query->executeUsingQueryCache(null, AbstractQuery::HYDRATE_ARRAY) ); assertType( - 'array', + 'mixed', $query->getSingleResult(AbstractQuery::HYDRATE_ARRAY) ); assertType( - 'array|null', + 'mixed', $query->getOneOrNullResult(AbstractQuery::HYDRATE_ARRAY) ); From 2ed35eafef6fe994c69a09739344edcd044acf53 Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Wed, 5 Apr 2023 19:58:58 +0200 Subject: [PATCH 04/11] Use benevolent union for scalar in queries --- .../Doctrine/Query/QueryResultTypeWalker.php | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/Type/Doctrine/Query/QueryResultTypeWalker.php b/src/Type/Doctrine/Query/QueryResultTypeWalker.php index 060dd092..38f0f382 100644 --- a/src/Type/Doctrine/Query/QueryResultTypeWalker.php +++ b/src/Type/Doctrine/Query/QueryResultTypeWalker.php @@ -795,7 +795,7 @@ public function walkSelectExpression($selectExpression) $type = $this->resolveDoctrineType($typeName, $enumType, $nullable); - $this->typeBuilder->addScalar($resultAlias, $type); + $this->addScalar($resultAlias, $type); return ''; } @@ -855,7 +855,7 @@ public function walkSelectExpression($selectExpression) }); } - $this->typeBuilder->addScalar($resultAlias, $type); + $this->addScalar($resultAlias, $type); return ''; } @@ -1276,6 +1276,18 @@ public function walkResultVariable($resultVariable) return $this->marshalType(new MixedType()); } + /** + * @param array-key $alias + */ + private function addScalar($alias, Type $type): void + { + if ($type instanceof UnionType) { + $type = TypeUtils::toBenevolentUnion($type); + } + + $this->typeBuilder->addScalar($alias, $type); + } + private function unmarshalType(string $marshalledType): Type { $type = unserialize($marshalledType); From 61a4dc1e87a41f2d2f7bcde34866e1e788334c3a Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Wed, 5 Apr 2023 21:04:39 +0200 Subject: [PATCH 05/11] Only use benevolent when where clause is used --- src/Type/Doctrine/Query/QueryResultTypeWalker.php | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/Type/Doctrine/Query/QueryResultTypeWalker.php b/src/Type/Doctrine/Query/QueryResultTypeWalker.php index 38f0f382..24ee22c1 100644 --- a/src/Type/Doctrine/Query/QueryResultTypeWalker.php +++ b/src/Type/Doctrine/Query/QueryResultTypeWalker.php @@ -107,6 +107,9 @@ class QueryResultTypeWalker extends SqlWalker /** @var bool */ private $hasGroupByClause; + /** @var bool */ + private $hasCondition; + /** * @param Query $query */ @@ -135,6 +138,7 @@ public function __construct($query, $parserResult, array $queryComponents) $this->nullableQueryComponents = []; $this->hasAggregateFunction = false; $this->hasGroupByClause = false; + $this->hasCondition = false; // The object is instantiated by Doctrine\ORM\Query\Parser, so receiving // dependencies through the constructor is not an option. Instead, we @@ -590,6 +594,8 @@ public function walkOrderByItem($orderByItem) */ public function walkHavingClause($havingClause) { + $this->hasCondition = true; + return $this->marshalType(new MixedType()); } @@ -994,6 +1000,8 @@ public function walkUpdateItem($updateItem) */ public function walkWhereClause($whereClause) { + $this->hasCondition = true; + return $this->marshalType(new MixedType()); } @@ -1281,7 +1289,10 @@ public function walkResultVariable($resultVariable) */ private function addScalar($alias, Type $type): void { - if ($type instanceof UnionType) { + // Since we don't check the condition inside the WHERE or HAVING + // conditions, we cannot be sure all the union types are correct. + // For exemple, a condition `WHERE foo.bar IS NOT NULL` could be added. + if ($this->hasCondition && $type instanceof UnionType) { $type = TypeUtils::toBenevolentUnion($type); } From aa3da277fc22d28e681086a74c3facc725119ec3 Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Wed, 5 Apr 2023 21:09:29 +0200 Subject: [PATCH 06/11] Use benevolent union when we cast values --- src/Type/Doctrine/Query/QueryResultTypeWalker.php | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/Type/Doctrine/Query/QueryResultTypeWalker.php b/src/Type/Doctrine/Query/QueryResultTypeWalker.php index 24ee22c1..dde0771a 100644 --- a/src/Type/Doctrine/Query/QueryResultTypeWalker.php +++ b/src/Type/Doctrine/Query/QueryResultTypeWalker.php @@ -847,18 +847,27 @@ public function walkSelectExpression($selectExpression) // the driver and PHP version. // Here we assume that the value may or may not be casted to // string by the driver. - $type = TypeTraverser::map($type, static function (Type $type, callable $traverse): Type { + $casted = false; + $type = TypeTraverser::map($type, static function (Type $type, callable $traverse) use (&$casted): Type { if ($type instanceof UnionType || $type instanceof IntersectionType) { return $traverse($type); } if ($type instanceof IntegerType || $type instanceof FloatType) { + $casted = true; return TypeCombinator::union($type->toString(), $type); } if ($type instanceof BooleanType) { + $casted = true; return TypeCombinator::union($type->toInteger()->toString(), $type); } return $traverse($type); }); + + // Since we made supposition about possibly casted values, + // we can only provide a benevolent union. + if ($casted && $type instanceof UnionType) { + $type = TypeUtils::toBenevolentUnion($type); + } } $this->addScalar($resultAlias, $type); From 1471e146c7b8e71af78c8f1122ad905a39125148 Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Thu, 6 Apr 2023 09:29:32 +0200 Subject: [PATCH 07/11] Fix tests --- .../Query/QueryResultTypeWalkerTest.php | 186 ++++++++++-------- 1 file changed, 100 insertions(+), 86 deletions(-) diff --git a/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php b/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php index 1393a9bc..46b031ea 100644 --- a/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php +++ b/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php @@ -13,6 +13,7 @@ use Doctrine\ORM\Tools\SchemaTool; use PHPStan\Testing\PHPStanTestCase; use PHPStan\Type\Accessory\AccessoryNumericStringType; +use PHPStan\Type\BenevolentUnionType; use PHPStan\Type\Constant\ConstantArrayTypeBuilder; use PHPStan\Type\Constant\ConstantIntegerType; use PHPStan\Type\Constant\ConstantStringType; @@ -28,6 +29,7 @@ use PHPStan\Type\StringType; use PHPStan\Type\Type; use PHPStan\Type\TypeCombinator; +use PHPStan\Type\TypeUtils; use PHPStan\Type\UnionType; use PHPStan\Type\VerbosityLevel; use QueryResult\Entities\Embedded; @@ -544,12 +546,12 @@ public function getTestData(): iterable ], [ new ConstantIntegerType(2), - TypeCombinator::union( + TypeUtils::toBenevolentUnion(TypeCombinator::union( new ConstantIntegerType(1), new ConstantIntegerType(2), new ConstantStringType('1'), new ConstantStringType('2') - ), + )), ], [ new ConstantIntegerType(3), @@ -596,7 +598,7 @@ public function getTestData(): iterable ], [ new ConstantIntegerType(1), - TypeCombinator::addNull($this->intStringified()), + $this->intStringified(true), ], [ new ConstantIntegerType(2), @@ -610,7 +612,7 @@ public function getTestData(): iterable ], [ new ConstantIntegerType(4), - TypeCombinator::addNull($this->intStringified()), + $this->intStringified(true), ], [ new ConstantIntegerType(5), @@ -620,7 +622,7 @@ public function getTestData(): iterable ], [ new ConstantIntegerType(6), - TypeCombinator::addNull($this->intStringified()), + $this->intStringified(true), ], [ new ConstantIntegerType(7), @@ -646,7 +648,7 @@ public function getTestData(): iterable ], [ new ConstantStringType('max'), - TypeCombinator::addNull($this->intStringified()), + $this->intStringified(true), ], [ new ConstantStringType('arithmetic'), @@ -678,10 +680,10 @@ public function getTestData(): iterable $this->constantArray([ [ new ConstantIntegerType(1), - TypeCombinator::union( + TypeUtils::toBenevolentUnion(TypeCombinator::union( new ConstantStringType('1'), new ConstantIntegerType(1) - ), + )), ], [new ConstantIntegerType(2), new ConstantStringType('hello')], ]), @@ -695,11 +697,11 @@ public function getTestData(): iterable $this->constantArray([ [ new ConstantIntegerType(1), - TypeCombinator::union( + TypeUtils::toBenevolentUnion(TypeCombinator::union( new ConstantIntegerType(1), new ConstantStringType('1'), new NullType() - ), + )), ], ]), ' @@ -712,10 +714,10 @@ public function getTestData(): iterable $this->constantArray([ [ new ConstantIntegerType(1), - TypeCombinator::union( + TypeUtils::toBenevolentUnion(TypeCombinator::union( new StringType(), new IntegerType() - ), + )), ], [ new ConstantIntegerType(2), @@ -741,10 +743,10 @@ public function getTestData(): iterable $this->constantArray([ [ new ConstantIntegerType(1), - TypeCombinator::union( + TypeUtils::toBenevolentUnion(TypeCombinator::union( new StringType(), new ConstantIntegerType(0) - ), + )), ], ]), ' @@ -761,10 +763,10 @@ public function getTestData(): iterable $this->constantArray([ [ new ConstantIntegerType(1), - TypeCombinator::union( + TypeUtils::toBenevolentUnion(TypeCombinator::union( new StringType(), new ConstantIntegerType(0) - ), + )), ], ]), ' @@ -781,12 +783,12 @@ public function getTestData(): iterable $this->constantArray([ [ new ConstantIntegerType(1), - TypeCombinator::union( + TypeUtils::toBenevolentUnion(TypeCombinator::union( new ConstantIntegerType(0), new ConstantIntegerType(1), new ConstantStringType('0'), new ConstantStringType('1') - ), + )), ], ]), ' @@ -802,12 +804,12 @@ public function getTestData(): iterable $this->constantArray([ [ new ConstantIntegerType(1), - TypeCombinator::union( + TypeUtils::toBenevolentUnion(TypeCombinator::union( new ConstantIntegerType(0), new ConstantIntegerType(1), new ConstantStringType('0'), new ConstantStringType('1') - ), + )), ], ]), ' @@ -823,31 +825,31 @@ public function getTestData(): iterable $this->constantArray([ [ new ConstantIntegerType(1), - TypeCombinator::union( + TypeUtils::toBenevolentUnion(TypeCombinator::union( new ConstantIntegerType(1), new ConstantStringType('1') - ), + )), ], [ new ConstantIntegerType(2), - TypeCombinator::union( + TypeUtils::toBenevolentUnion(TypeCombinator::union( new ConstantIntegerType(0), new ConstantStringType('0') - ), + )), ], [ new ConstantIntegerType(3), - TypeCombinator::union( + TypeUtils::toBenevolentUnion(TypeCombinator::union( new ConstantIntegerType(1), new ConstantStringType('1') - ), + )), ], [ new ConstantIntegerType(4), - TypeCombinator::union( + TypeUtils::toBenevolentUnion(TypeCombinator::union( new ConstantIntegerType(0), new ConstantStringType('0') - ), + )), ], ]), ' @@ -1019,10 +1021,10 @@ public function getTestData(): iterable ], [ new ConstantIntegerType(2), - TypeCombinator::union( + TypeUtils::toBenevolentUnion(TypeCombinator::union( new ConstantIntegerType(1), new ConstantStringType('1') - ), + )), ], [ new ConstantStringType('intColumn'), @@ -1066,7 +1068,7 @@ public function getTestData(): iterable yield 'new arguments affect scalar counter' => [ $this->constantArray([ - [new ConstantIntegerType(5), TypeCombinator::addNull($this->intStringified())], + [new ConstantIntegerType(5), $this->intStringified(true)], [new ConstantIntegerType(0), new ObjectType(ManyId::class)], [new ConstantIntegerType(1), new ObjectType(OneId::class)], ]), @@ -1083,7 +1085,7 @@ public function getTestData(): iterable [new ConstantStringType('intColumn'), new IntegerType()], [new ConstantIntegerType(1), $this->intStringified()], [new ConstantIntegerType(2), $this->intStringified()], - [new ConstantIntegerType(3), TypeCombinator::addNull($this->intStringified())], + [new ConstantIntegerType(3), $this->intStringified(true)], [new ConstantIntegerType(4), $this->intStringified()], [new ConstantIntegerType(5), $this->intStringified()], [new ConstantIntegerType(6), $this->numericStringified()], @@ -1105,9 +1107,9 @@ public function getTestData(): iterable yield 'abs function' => [ $this->constantArray([ [new ConstantIntegerType(1), $this->unumericStringified()], - [new ConstantIntegerType(2), TypeCombinator::addNull($this->unumericStringified())], + [new ConstantIntegerType(2), $this->unumericStringified(true)], [new ConstantIntegerType(3), $this->unumericStringified()], - [new ConstantIntegerType(4), TypeCombinator::union($this->unumericStringified())], + [new ConstantIntegerType(4), $this->unumericStringified()], ]), ' SELECT ABS(m.intColumn), @@ -1121,7 +1123,7 @@ public function getTestData(): iterable yield 'bit_and function' => [ $this->constantArray([ [new ConstantIntegerType(1), $this->uintStringified()], - [new ConstantIntegerType(2), TypeCombinator::addNull($this->uintStringified())], + [new ConstantIntegerType(2), $this->uintStringified(true)], [new ConstantIntegerType(3), $this->uintStringified()], ]), ' @@ -1135,7 +1137,7 @@ public function getTestData(): iterable yield 'bit_or function' => [ $this->constantArray([ [new ConstantIntegerType(1), $this->uintStringified()], - [new ConstantIntegerType(2), TypeCombinator::addNull($this->uintStringified())], + [new ConstantIntegerType(2), $this->uintStringified(true)], [new ConstantIntegerType(3), $this->uintStringified()], ]), ' @@ -1211,8 +1213,8 @@ public function getTestData(): iterable yield 'date_diff function' => [ $this->constantArray([ [new ConstantIntegerType(1), $this->numericStringified()], - [new ConstantIntegerType(2), TypeCombinator::addNull($this->numericStringified())], - [new ConstantIntegerType(3), TypeCombinator::addNull($this->numericStringified())], + [new ConstantIntegerType(2), $this->numericStringified(true)], + [new ConstantIntegerType(3), $this->numericStringified(true)], [new ConstantIntegerType(4), $this->numericStringified()], ]), ' @@ -1254,11 +1256,9 @@ public function getTestData(): iterable ], [ new ConstantIntegerType(2), - TypeCombinator::addNull( - $this->hasTypedExpressions() - ? $this->uint() - : $this->uintStringified() - ), + $this->hasTypedExpressions() + ? $this->uint(true) + : $this->uintStringified(true) ], [ new ConstantIntegerType(3), @@ -1279,8 +1279,8 @@ public function getTestData(): iterable yield 'locate function' => [ $this->constantArray([ [new ConstantIntegerType(1), $this->uintStringified()], - [new ConstantIntegerType(2), TypeCombinator::addNull($this->uintStringified())], - [new ConstantIntegerType(3), TypeCombinator::addNull($this->uintStringified())], + [new ConstantIntegerType(2), $this->uintStringified(true)], + [new ConstantIntegerType(3), $this->uintStringified(true)], [new ConstantIntegerType(4), $this->uintStringified()], ]), ' @@ -1322,8 +1322,8 @@ public function getTestData(): iterable yield 'mod function' => [ $this->constantArray([ [new ConstantIntegerType(1), $this->uintStringified()], - [new ConstantIntegerType(2), TypeCombinator::addNull($this->uintStringified())], - [new ConstantIntegerType(3), TypeCombinator::addNull($this->uintStringified())], + [new ConstantIntegerType(2), $this->uintStringified(true)], + [new ConstantIntegerType(3), $this->uintStringified(true)], [new ConstantIntegerType(4), $this->uintStringified()], ]), ' @@ -1337,7 +1337,7 @@ public function getTestData(): iterable yield 'mod function error' => [ $this->constantArray([ - [new ConstantIntegerType(1), TypeCombinator::addNull($this->uintStringified())], + [new ConstantIntegerType(1), $this->uintStringified(true)], ]), ' SELECT MOD(10, NULLIF(m.intColumn, m.intColumn)) @@ -1396,15 +1396,15 @@ public function getTestData(): iterable yield 'identity function' => [ $this->constantArray([ - [new ConstantIntegerType(1), TypeCombinator::addNull($this->numericStringOrInt())], - [new ConstantIntegerType(2), $this->numericStringOrInt()], - [new ConstantIntegerType(3), TypeCombinator::addNull($this->numericStringOrInt())], + [new ConstantIntegerType(1), $this->intStringified(true)], + [new ConstantIntegerType(2), $this->intStringified()], + [new ConstantIntegerType(3), $this->intStringified(true)], [new ConstantIntegerType(4), TypeCombinator::addNull(new StringType())], [new ConstantIntegerType(5), TypeCombinator::addNull(new StringType())], - [new ConstantIntegerType(6), TypeCombinator::addNull($this->numericStringOrInt())], + [new ConstantIntegerType(6), $this->intStringified(true)], [new ConstantIntegerType(7), TypeCombinator::addNull(new MixedType())], - [new ConstantIntegerType(8), TypeCombinator::addNull($this->numericStringOrInt())], - [new ConstantIntegerType(9), TypeCombinator::addNull($this->numericStringOrInt())], + [new ConstantIntegerType(8), $this->intStringified(true)], + [new ConstantIntegerType(9), $this->intStringified(true)], ]), ' SELECT IDENTITY(m.oneNull), @@ -1423,7 +1423,7 @@ public function getTestData(): iterable yield 'select nullable association' => [ $this->constantArray([ - [new ConstantIntegerType(1), TypeCombinator::addNull($this->numericStringOrInt())], + [new ConstantIntegerType(1), $this->intStringified(true)], ]), ' SELECT DISTINCT(m.oneNull) @@ -1433,7 +1433,7 @@ public function getTestData(): iterable yield 'select non null association' => [ $this->constantArray([ - [new ConstantIntegerType(1), $this->numericStringOrInt()], + [new ConstantIntegerType(1), $this->intStringified()], ]), ' SELECT DISTINCT(m.one) @@ -1443,7 +1443,7 @@ public function getTestData(): iterable yield 'select default nullability association' => [ $this->constantArray([ - [new ConstantIntegerType(1), TypeCombinator::addNull($this->numericStringOrInt())], + [new ConstantIntegerType(1), $this->intStringified(true)], ]), ' SELECT DISTINCT(m.oneDefaultNullability) @@ -1453,7 +1453,7 @@ public function getTestData(): iterable yield 'select non null association in aggregated query' => [ $this->constantArray([ - [new ConstantIntegerType(1), TypeCombinator::addNull($this->numericStringOrInt())], + [new ConstantIntegerType(1), $this->intStringified(true)], [ new ConstantIntegerType(2), $this->hasTypedExpressions() @@ -1523,17 +1523,6 @@ private function constantArray(array $elements): Type return $builder->getArray(); } - private function numericStringOrInt(): Type - { - return new UnionType([ - new IntegerType(), - new IntersectionType([ - new StringType(), - new AccessoryNumericStringType(), - ]), - ]); - } - private function numericString(): Type { return new IntersectionType([ @@ -1542,42 +1531,67 @@ private function numericString(): Type ]); } - private function uint(): Type + private function uint(bool $nullable = false): Type { - return IntegerRangeType::fromInterval(0, null); + $type = IntegerRangeType::fromInterval(0, null); + if ($nullable) { + TypeCombinator::addNull($type); + } + + return $type; } - private function intStringified(): Type + private function intStringified(bool $nullable = false): Type { - return TypeCombinator::union( + $types = [ new IntegerType(), - $this->numericString() - ); + $this->numericString(), + ]; + if ($nullable) { + $types[] = new NullType(); + } + + return TypeUtils::toBenevolentUnion(TypeCombinator::union(...$types)); } - private function uintStringified(): Type + private function uintStringified(bool $nullable = false): Type { - return TypeCombinator::union( + $types = [ $this->uint(), - $this->numericString() - ); + $this->numericString(), + ]; + if ($nullable) { + $types[] = new NullType(); + } + + return TypeUtils::toBenevolentUnion(TypeCombinator::union(...$types)); } - private function numericStringified(): Type + private function numericStringified(bool $nullable = false): Type { - return TypeCombinator::union( + $types = [ new FloatType(), new IntegerType(), - $this->numericString() - ); + $this->numericString(), + ]; + if ($nullable) { + $types[] = new NullType(); + } + + return TypeUtils::toBenevolentUnion(TypeCombinator::union(...$types)); } - private function unumericStringified(): Type + private function unumericStringified(bool $nullable = false): Type { - return TypeCombinator::union( + $types = [ new FloatType(), IntegerRangeType::fromInterval(0, null), $this->numericString() - ); + ]; + if ($nullable) { + $types[] = new NullType(); + } + + return TypeUtils::toBenevolentUnion(TypeCombinator::union(...$types)); } private function hasTypedExpressions(): bool From 157d52156bb6ba6e4321aa3f60d9d9d581138260 Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Thu, 6 Apr 2023 09:43:46 +0200 Subject: [PATCH 08/11] Avoid useless benevolent unions --- src/Type/Doctrine/Query/QueryResultTypeWalker.php | 4 +++- .../Doctrine/Query/QueryResultTypeWalkerTest.php | 12 ++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/Type/Doctrine/Query/QueryResultTypeWalker.php b/src/Type/Doctrine/Query/QueryResultTypeWalker.php index dde0771a..a04742e6 100644 --- a/src/Type/Doctrine/Query/QueryResultTypeWalker.php +++ b/src/Type/Doctrine/Query/QueryResultTypeWalker.php @@ -848,6 +848,8 @@ public function walkSelectExpression($selectExpression) // Here we assume that the value may or may not be casted to // string by the driver. $casted = false; + $originalType = $type; + $type = TypeTraverser::map($type, static function (Type $type, callable $traverse) use (&$casted): Type { if ($type instanceof UnionType || $type instanceof IntersectionType) { return $traverse($type); @@ -865,7 +867,7 @@ public function walkSelectExpression($selectExpression) // Since we made supposition about possibly casted values, // we can only provide a benevolent union. - if ($casted && $type instanceof UnionType) { + if ($casted && $type instanceof UnionType && !$originalType->equals($type)) { $type = TypeUtils::toBenevolentUnion($type); } } diff --git a/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php b/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php index 46b031ea..87cce369 100644 --- a/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php +++ b/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php @@ -714,10 +714,10 @@ public function getTestData(): iterable $this->constantArray([ [ new ConstantIntegerType(1), - TypeUtils::toBenevolentUnion(TypeCombinator::union( + TypeCombinator::union( new StringType(), new IntegerType() - )), + ), ], [ new ConstantIntegerType(2), @@ -743,10 +743,10 @@ public function getTestData(): iterable $this->constantArray([ [ new ConstantIntegerType(1), - TypeUtils::toBenevolentUnion(TypeCombinator::union( + TypeCombinator::union( new StringType(), new ConstantIntegerType(0) - )), + ), ], ]), ' @@ -763,10 +763,10 @@ public function getTestData(): iterable $this->constantArray([ [ new ConstantIntegerType(1), - TypeUtils::toBenevolentUnion(TypeCombinator::union( + TypeCombinator::union( new StringType(), new ConstantIntegerType(0) - )), + ), ], ]), ' From 3a2153a9eeb467fc4d1693e1829607dcf3fa9980 Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Thu, 6 Apr 2023 09:51:03 +0200 Subject: [PATCH 09/11] Fix more tests --- .../QueryResultDynamicReturnTypeExtension.php | 9 ++++++++- .../Doctrine/Query/QueryResultTypeWalkerTest.php | 6 ++---- .../Type/Doctrine/data/QueryResult/queryResult.php | 14 +++++++------- 3 files changed, 17 insertions(+), 12 deletions(-) diff --git a/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php b/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php index 7d047768..96b3f7bc 100644 --- a/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php +++ b/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php @@ -10,6 +10,7 @@ use PHPStan\ShouldNotHappenException; use PHPStan\Type\Accessory\AccessoryArrayListType; use PHPStan\Type\ArrayType; +use PHPStan\Type\BenevolentUnionType; use PHPStan\Type\Constant\ConstantIntegerType; use PHPStan\Type\Doctrine\ObjectMetadataResolver; use PHPStan\Type\DynamicMethodReturnTypeExtension; @@ -21,6 +22,7 @@ use PHPStan\Type\Type; use PHPStan\Type\TypeCombinator; use PHPStan\Type\TypeTraverser; +use PHPStan\Type\TypeUtils; use PHPStan\Type\TypeWithClassName; use PHPStan\Type\VoidType; use function count; @@ -156,7 +158,12 @@ private function getMethodReturnTypeForHydrationMode( case 'getSingleResult': return $queryResultType; case 'getOneOrNullResult': - return TypeCombinator::addNull($queryResultType); + $nullableQueryResultType = TypeCombinator::addNull($queryResultType); + if ($queryResultType instanceof BenevolentUnionType) { + $nullableQueryResultType = TypeUtils::toBenevolentUnion($nullableQueryResultType); + } + + return $nullableQueryResultType; case 'toIterable': return new IterableType( $queryKeyType->isNull()->yes() ? new IntegerType() : $queryKeyType, diff --git a/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php b/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php index 87cce369..d42afe79 100644 --- a/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php +++ b/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php @@ -13,7 +13,6 @@ use Doctrine\ORM\Tools\SchemaTool; use PHPStan\Testing\PHPStanTestCase; use PHPStan\Type\Accessory\AccessoryNumericStringType; -use PHPStan\Type\BenevolentUnionType; use PHPStan\Type\Constant\ConstantArrayTypeBuilder; use PHPStan\Type\Constant\ConstantIntegerType; use PHPStan\Type\Constant\ConstantStringType; @@ -30,7 +29,6 @@ use PHPStan\Type\Type; use PHPStan\Type\TypeCombinator; use PHPStan\Type\TypeUtils; -use PHPStan\Type\UnionType; use PHPStan\Type\VerbosityLevel; use QueryResult\Entities\Embedded; use QueryResult\Entities\JoinedChild; @@ -1258,7 +1256,7 @@ public function getTestData(): iterable new ConstantIntegerType(2), $this->hasTypedExpressions() ? $this->uint(true) - : $this->uintStringified(true) + : $this->uintStringified(true), ], [ new ConstantIntegerType(3), @@ -1585,7 +1583,7 @@ private function unumericStringified(bool $nullable = false): Type $types = [ new FloatType(), IntegerRangeType::fromInterval(0, null), - $this->numericString() + $this->numericString(), ]; if ($nullable) { $types[] = new NullType(); diff --git a/tests/Type/Doctrine/data/QueryResult/queryResult.php b/tests/Type/Doctrine/data/QueryResult/queryResult.php index 272744df..d6972943 100644 --- a/tests/Type/Doctrine/data/QueryResult/queryResult.php +++ b/tests/Type/Doctrine/data/QueryResult/queryResult.php @@ -384,31 +384,31 @@ public function testReturnTypeOfQueryMethodsWithExplicitSingleScalarHydrationMod '); assertType( - 'int<0, max>|numeric-string', + '(int<0, max>|numeric-string)', $query->getResult(AbstractQuery::HYDRATE_SINGLE_SCALAR) ); assertType( - 'int<0, max>|numeric-string', + '(int<0, max>|numeric-string)', $query->getSingleScalarResult() ); assertType( - 'int<0, max>|numeric-string', + '(int<0, max>|numeric-string)', $query->execute(null, AbstractQuery::HYDRATE_SINGLE_SCALAR) ); assertType( - 'int<0, max>|numeric-string', + '(int<0, max>|numeric-string)', $query->executeIgnoreQueryCache(null, AbstractQuery::HYDRATE_SINGLE_SCALAR) ); assertType( - 'int<0, max>|numeric-string', + '(int<0, max>|numeric-string)', $query->executeUsingQueryCache(null, AbstractQuery::HYDRATE_SINGLE_SCALAR) ); assertType( - 'int<0, max>|numeric-string', + '(int<0, max>|numeric-string)', $query->getSingleResult(AbstractQuery::HYDRATE_SINGLE_SCALAR) ); assertType( - 'int<0, max>|numeric-string|null', + '(int<0, max>|numeric-string|null)', $query->getOneOrNullResult(AbstractQuery::HYDRATE_SINGLE_SCALAR) ); } From b8d290e6760a329569aa393d359805962644465c Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Thu, 6 Apr 2023 10:27:06 +0200 Subject: [PATCH 10/11] Fix check for where condition --- .../Doctrine/Query/QueryResultTypeWalker.php | 13 +++++-------- .../Query/QueryResultTypeWalkerTest.php | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/Type/Doctrine/Query/QueryResultTypeWalker.php b/src/Type/Doctrine/Query/QueryResultTypeWalker.php index a04742e6..e43afa88 100644 --- a/src/Type/Doctrine/Query/QueryResultTypeWalker.php +++ b/src/Type/Doctrine/Query/QueryResultTypeWalker.php @@ -108,7 +108,7 @@ class QueryResultTypeWalker extends SqlWalker private $hasGroupByClause; /** @var bool */ - private $hasCondition; + private $hasWhereClause; /** * @param Query $query @@ -138,7 +138,7 @@ public function __construct($query, $parserResult, array $queryComponents) $this->nullableQueryComponents = []; $this->hasAggregateFunction = false; $this->hasGroupByClause = false; - $this->hasCondition = false; + $this->hasWhereClause = false; // The object is instantiated by Doctrine\ORM\Query\Parser, so receiving // dependencies through the constructor is not an option. Instead, we @@ -181,6 +181,7 @@ public function walkSelectStatement(AST\SelectStatement $AST) $this->typeBuilder->setSelectQuery(); $this->hasAggregateFunction = $this->hasAggregateFunction($AST); $this->hasGroupByClause = $AST->groupByClause !== null; + $this->hasWhereClause = $AST->whereClause !== null; $this->walkFromClause($AST->fromClause); @@ -594,8 +595,6 @@ public function walkOrderByItem($orderByItem) */ public function walkHavingClause($havingClause) { - $this->hasCondition = true; - return $this->marshalType(new MixedType()); } @@ -1011,8 +1010,6 @@ public function walkUpdateItem($updateItem) */ public function walkWhereClause($whereClause) { - $this->hasCondition = true; - return $this->marshalType(new MixedType()); } @@ -1300,10 +1297,10 @@ public function walkResultVariable($resultVariable) */ private function addScalar($alias, Type $type): void { - // Since we don't check the condition inside the WHERE or HAVING + // Since we don't check the condition inside the WHERE // conditions, we cannot be sure all the union types are correct. // For exemple, a condition `WHERE foo.bar IS NOT NULL` could be added. - if ($this->hasCondition && $type instanceof UnionType) { + if ($this->hasWhereClause && $type instanceof UnionType) { $type = TypeUtils::toBenevolentUnion($type); } diff --git a/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php b/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php index d42afe79..7bbbd206 100644 --- a/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php +++ b/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php @@ -442,6 +442,25 @@ public function getTestData(): iterable ', ]; + yield 'scalar with where condition' => [ + $this->constantArray([ + [new ConstantStringType('intColumn'), new IntegerType()], + [new ConstantStringType('stringColumn'), new StringType()], + [ + new ConstantStringType('stringNullColumn'), + TypeUtils::toBenevolentUnion(TypeCombinator::addNull(new StringType())) + ], + [new ConstantStringType('datetimeColumn'), new ObjectType(DateTime::class)], + [new ConstantStringType('datetimeImmutableColumn'), new ObjectType(DateTimeImmutable::class)], + ]), + ' + SELECT m.intColumn, m.stringColumn, m.stringNullColumn, + m.datetimeColumn, m.datetimeImmutableColumn + FROM QueryResult\Entities\Many m + WHERE m.stringNullColumn IS NOT NULL + ', + ]; + yield 'scalar with alias' => [ $this->constantArray([ [new ConstantStringType('i'), new IntegerType()], From a268dbc075bc2a0ecdef0fc9ca1ce715a359df5b Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Thu, 6 Apr 2023 10:37:39 +0200 Subject: [PATCH 11/11] Fix cs --- tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php b/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php index 7bbbd206..9fb20455 100644 --- a/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php +++ b/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php @@ -448,7 +448,7 @@ public function getTestData(): iterable [new ConstantStringType('stringColumn'), new StringType()], [ new ConstantStringType('stringNullColumn'), - TypeUtils::toBenevolentUnion(TypeCombinator::addNull(new StringType())) + TypeUtils::toBenevolentUnion(TypeCombinator::addNull(new StringType())), ], [new ConstantStringType('datetimeColumn'), new ObjectType(DateTime::class)], [new ConstantStringType('datetimeImmutableColumn'), new ObjectType(DateTimeImmutable::class)],