88use PHPStan \Reflection \MethodReflection ;
99use PHPStan \Reflection \ParametersAcceptorSelector ;
1010use PHPStan \ShouldNotHappenException ;
11+ use PHPStan \Type \Accessory \AccessoryArrayListType ;
1112use PHPStan \Type \ArrayType ;
1213use PHPStan \Type \Constant \ConstantIntegerType ;
1314use PHPStan \Type \DynamicMethodReturnTypeExtension ;
@@ -71,10 +72,12 @@ public function getTypeFromMethodCall(
7172
7273 $ queryType = $ scope ->getType ($ methodCall ->var );
7374 $ queryResultType = $ this ->getQueryResultType ($ queryType );
75+ $ queryKeyType = $ this ->getQueryKeyType ($ queryType );
7476
7577 return $ this ->getMethodReturnTypeForHydrationMode (
7678 $ methodReflection ,
7779 $ hydrationMode ,
80+ $ queryKeyType ,
7881 $ queryResultType
7982 );
8083 }
@@ -93,9 +96,24 @@ private function getQueryResultType(Type $queryType): Type
9396 return $ resultType ;
9497 }
9598
99+ private function getQueryKeyType (Type $ queryType ): Type
100+ {
101+ if (!$ queryType instanceof TypeWithClassName) {
102+ return new MixedType ();
103+ }
104+
105+ $ resultType = GenericTypeVariableResolver::getType ($ queryType , AbstractQuery::class, 'TKey ' );
106+ if ($ resultType === null ) {
107+ return new MixedType ();
108+ }
109+
110+ return $ resultType ;
111+ }
112+
96113 private function getMethodReturnTypeForHydrationMode (
97114 MethodReflection $ methodReflection ,
98115 Type $ hydrationMode ,
116+ Type $ queryKeyType ,
99117 Type $ queryResultType
100118 ): Type
101119 {
@@ -126,12 +144,18 @@ private function getMethodReturnTypeForHydrationMode(
126144 return TypeCombinator::addNull ($ queryResultType );
127145 case 'toIterable ' :
128146 return new IterableType (
129- new MixedType () ,
147+ $ queryKeyType instanceof NullType ? new IntegerType () : $ queryKeyType ,
130148 $ queryResultType
131149 );
132150 default :
151+ if ($ queryKeyType instanceof NullType) {
152+ return AccessoryArrayListType::intersectWith (new ArrayType (
153+ new IntegerType (),
154+ $ queryResultType
155+ ));
156+ }
133157 return new ArrayType (
134- new MixedType () ,
158+ $ queryKeyType ,
135159 $ queryResultType
136160 );
137161 }
0 commit comments