diff --git a/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php b/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php index 20e23831..96b3f7bc 100644 --- a/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php +++ b/src/Type/Doctrine/Query/QueryResultDynamicReturnTypeExtension.php @@ -10,14 +10,22 @@ 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; 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\TypeUtils; +use PHPStan\Type\TypeWithClassName; use PHPStan\Type\VoidType; +use function count; final class QueryResultDynamicReturnTypeExtension implements DynamicMethodReturnTypeExtension { @@ -32,6 +40,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 +64,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 +76,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,23 +126,54 @@ 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; 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, $queryResultType ); default: + if ($singleResult) { + return $queryResultType; + } + if ($queryKeyType->isNull()->yes()) { return AccessoryArrayListType::intersectWith(new ArrayType( new IntegerType(), @@ -128,13 +187,104 @@ 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(); + } + + 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(); + } + ); + } + + private function getScalarHydratedReturnType(Type $queryResultType): Type + { + if (!$queryResultType->isArray()->yes()) { + return new ArrayType(new MixedType(), new MixedType()); + } + + foreach ($queryResultType->getArrays() as $arrayType) { + $itemType = $arrayType->getItemType(); + + if ( + !(new ObjectWithoutClassType())->isSuperTypeOf($itemType)->no() + || !$itemType->isArray()->no() + ) { + return new ArrayType(new MixedType(), new MixedType()); + } + } + + return $queryResultType; + } + + private function getSimpleObjectHydratedReturnType(Type $queryResultType): Type + { + if ((new ObjectWithoutClassType())->isSuperTypeOf($queryResultType)->yes()) { + return $queryResultType; + } + + return new MixedType(); + } + + private function getSingleScalarHydratedReturnType(Type $queryResultType): Type { - if (!$type instanceof ConstantIntegerType) { - return false; + $queryResultType = $this->getScalarHydratedReturnType($queryResultType); + if (!$queryResultType->isConstantArray()->yes()) { + return new MixedType(); + } + + $types = []; + foreach ($queryResultType->getConstantArrays() as $constantArrayType) { + $values = $constantArrayType->getValueTypes(); + if (count($values) !== 1) { + return new MixedType(); + } + + $types[] = $constantArrayType->getFirstIterableValueType(); + } + + return TypeCombinator::union(...$types); + } + + private function getScalarColumnHydratedReturnType(Type $queryResultType): Type + { + $queryResultType = $this->getScalarHydratedReturnType($queryResultType); + if (!$queryResultType->isConstantArray()->yes()) { + return new MixedType(); + } + + $types = []; + foreach ($queryResultType->getConstantArrays() as $constantArrayType) { + $values = $constantArrayType->getValueTypes(); + if (count($values) !== 1) { + return new MixedType(); + } + + $types[] = $constantArrayType->getFirstIterableValueType(); } - return $type->getValue() === AbstractQuery::HYDRATE_OBJECT; + return TypeCombinator::union(...$types); } private function originalReturnType(MethodReflection $methodReflection): Type diff --git a/src/Type/Doctrine/Query/QueryResultTypeWalker.php b/src/Type/Doctrine/Query/QueryResultTypeWalker.php index 060dd092..e43afa88 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 $hasWhereClause; + /** * @param Query $query */ @@ -135,6 +138,7 @@ public function __construct($query, $parserResult, array $queryComponents) $this->nullableQueryComponents = []; $this->hasAggregateFunction = false; $this->hasGroupByClause = 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 @@ -177,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); @@ -795,7 +800,7 @@ public function walkSelectExpression($selectExpression) $type = $this->resolveDoctrineType($typeName, $enumType, $nullable); - $this->typeBuilder->addScalar($resultAlias, $type); + $this->addScalar($resultAlias, $type); return ''; } @@ -841,21 +846,32 @@ 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; + $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); } 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 && !$originalType->equals($type)) { + $type = TypeUtils::toBenevolentUnion($type); + } } - $this->typeBuilder->addScalar($resultAlias, $type); + $this->addScalar($resultAlias, $type); return ''; } @@ -1276,6 +1292,21 @@ public function walkResultVariable($resultVariable) return $this->marshalType(new MixedType()); } + /** + * @param array-key $alias + */ + private function addScalar($alias, Type $type): void + { + // 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->hasWhereClause && $type instanceof UnionType) { + $type = TypeUtils::toBenevolentUnion($type); + } + + $this->typeBuilder->addScalar($alias, $type); + } + private function unmarshalType(string $marshalledType): Type { $type = unserialize($marshalledType); diff --git a/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php b/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php index 1393a9bc..9fb20455 100644 --- a/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php +++ b/tests/Type/Doctrine/Query/QueryResultTypeWalkerTest.php @@ -28,7 +28,7 @@ use PHPStan\Type\StringType; use PHPStan\Type\Type; use PHPStan\Type\TypeCombinator; -use PHPStan\Type\UnionType; +use PHPStan\Type\TypeUtils; use PHPStan\Type\VerbosityLevel; use QueryResult\Entities\Embedded; use QueryResult\Entities\JoinedChild; @@ -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()], @@ -544,12 +563,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 +615,7 @@ public function getTestData(): iterable ], [ new ConstantIntegerType(1), - TypeCombinator::addNull($this->intStringified()), + $this->intStringified(true), ], [ new ConstantIntegerType(2), @@ -610,7 +629,7 @@ public function getTestData(): iterable ], [ new ConstantIntegerType(4), - TypeCombinator::addNull($this->intStringified()), + $this->intStringified(true), ], [ new ConstantIntegerType(5), @@ -620,7 +639,7 @@ public function getTestData(): iterable ], [ new ConstantIntegerType(6), - TypeCombinator::addNull($this->intStringified()), + $this->intStringified(true), ], [ new ConstantIntegerType(7), @@ -646,7 +665,7 @@ public function getTestData(): iterable ], [ new ConstantStringType('max'), - TypeCombinator::addNull($this->intStringified()), + $this->intStringified(true), ], [ new ConstantStringType('arithmetic'), @@ -678,10 +697,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 +714,11 @@ public function getTestData(): iterable $this->constantArray([ [ new ConstantIntegerType(1), - TypeCombinator::union( + TypeUtils::toBenevolentUnion(TypeCombinator::union( new ConstantIntegerType(1), new ConstantStringType('1'), new NullType() - ), + )), ], ]), ' @@ -781,12 +800,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 +821,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 +842,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 +1038,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 +1085,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 +1102,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 +1124,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 +1140,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 +1154,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 +1230,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 +1273,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 +1296,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 +1339,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 +1354,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 +1413,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 +1440,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 +1450,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 +1460,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 +1470,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 +1540,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 +1548,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() - ); + $this->numericString(), + ]; + if ($nullable) { + $types[] = new NullType(); + } + + return TypeUtils::toBenevolentUnion(TypeCombinator::union(...$types)); } private function hasTypedExpressions(): bool diff --git a/tests/Type/Doctrine/data/QueryResult/queryResult.php b/tests/Type/Doctrine/data/QueryResult/queryResult.php index 02469e46..d6972943 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,23 +156,27 @@ 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( @@ -183,6 +187,382 @@ public function testReturnTypeOfQueryMethodsWithExplicitNonObjectHydrationMode(E 'mixed', $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) + ); } /**