Skip to content

Commit 813afaa

Browse files
authored
Fix type when using \PDO::FETCH_OBJ on iteration (#751)
* Fix type when using \PDO::FETCH_OBJ on iteration * fix * Update PdoStatementObjectType.php
1 parent 4827561 commit 813afaa

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

src/PdoReflection/PdoStatementObjectType.php

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,11 @@
1313
use PHPStan\Type\FloatType;
1414
use PHPStan\Type\IntegerRangeType;
1515
use PHPStan\Type\IntegerType;
16+
use PHPStan\Type\IntersectionType;
1617
use PHPStan\Type\IsSuperTypeOfResult;
1718
use PHPStan\Type\MixedType;
1819
use PHPStan\Type\NullType;
20+
use PHPStan\Type\ObjectShapeType;
1921
use PHPStan\Type\ObjectType;
2022
use PHPStan\Type\StringType;
2123
use PHPStan\Type\Type;
@@ -102,7 +104,21 @@ private function reduceBothType(Type $bothType, int $fetchType): Type
102104
}
103105

104106
if (QueryReflector::FETCH_TYPE_CLASS === $fetchType) {
105-
return new ArrayType(new IntegerType(), new ObjectType('stdClass'));
107+
$keyTypes = $bothType->getKeyTypes();
108+
$valueTypes = $bothType->getValueTypes();
109+
110+
$properties = [];
111+
foreach ($keyTypes as $i => $keyType) {
112+
if (! $keyType->isString()->yes()) {
113+
continue;
114+
}
115+
$properties[(string) $keyType->getValue()] = $valueTypes[$i];
116+
}
117+
118+
return new IntersectionType([
119+
new ObjectType(\stdClass::class),
120+
new ObjectShapeType($properties, []),
121+
]);
106122
}
107123

108124
// both types contains numeric and string keys, therefore the count is doubled

tests/default/data/pdo-fetch-types.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ public function supportedFetchTypes(PDO $pdo)
3232

3333
$stmt = $pdo->query('SELECT email, adaid FROM ada', PDO::FETCH_OBJ);
3434
foreach ($stmt as $row) {
35-
assertType('array<int, stdClass>', $row);
35+
assertType('object{email: string, adaid: int<-32768, 32767>}&stdClass', $row);
3636
}
3737
}
3838

0 commit comments

Comments
 (0)