2121use PHPStan \Type \BenevolentUnionType ;
2222use PHPStan \Type \Constant \ConstantArrayType ;
2323use PHPStan \Type \Constant \ConstantArrayTypeBuilder ;
24+ use PHPStan \Type \Constant \ConstantBooleanType ;
2425use PHPStan \Type \DynamicFunctionReturnTypeExtension ;
2526use PHPStan \Type \MixedType ;
2627use PHPStan \Type \NeverType ;
@@ -170,12 +171,12 @@ private function filterByTruthyValue(Scope $scope, Error|Variable|null $itemVar,
170171 $ builder = ConstantArrayTypeBuilder::createEmpty ();
171172 foreach ($ constantArray ->getKeyTypes () as $ i => $ keyType ) {
172173 $ itemType = $ constantArray ->getValueTypes ()[$ i ];
173- [$ newKeyType , $ newItemType ] = $ this ->processKeyAndItemType ($ scope , $ keyType , $ itemType , $ itemVar , $ keyVar , $ expr );
174+ [$ newKeyType , $ newItemType, $ optional ] = $ this ->processKeyAndItemType ($ scope , $ keyType , $ itemType , $ itemVar , $ keyVar , $ expr );
174175 if ($ newKeyType instanceof NeverType || $ newItemType instanceof NeverType) {
175176 continue ;
176177 }
177178 if ($ itemType ->equals ($ newItemType ) && $ keyType ->equals ($ newKeyType )) {
178- $ builder ->setOffsetValueType ($ keyType , $ itemType );
179+ $ builder ->setOffsetValueType ($ keyType , $ itemType, $ optional );
179180 continue ;
180181 }
181182
@@ -198,7 +199,7 @@ private function filterByTruthyValue(Scope $scope, Error|Variable|null $itemVar,
198199 }
199200
200201 /**
201- * @return array{Type, Type}
202+ * @return array{Type, Type, bool }
202203 */
203204 private function processKeyAndItemType (MutatingScope $ scope , Type $ keyType , Type $ itemType , Error |Variable |null $ itemVar , Error |Variable |null $ keyVar , Expr $ expr ): array
204205 {
@@ -220,11 +221,13 @@ private function processKeyAndItemType(MutatingScope $scope, Type $keyType, Type
220221 $ scope = $ scope ->assignVariable ($ keyVarName , $ keyType );
221222 }
222223
224+ $ booleanResult = $ scope ->getType ($ expr )->toBoolean ();
223225 $ scope = $ scope ->filterByTruthyValue ($ expr );
224226
225227 return [
226228 $ keyVarName !== null ? $ scope ->getVariableType ($ keyVarName ) : $ keyType ,
227229 $ itemVarName !== null ? $ scope ->getVariableType ($ itemVarName ) : $ itemType ,
230+ !$ booleanResult instanceof ConstantBooleanType,
228231 ];
229232 }
230233
0 commit comments