From 6670092593da0fd0696c8ed1ad37ff0098f2dbd5 Mon Sep 17 00:00:00 2001 From: "John Paul E. Balandan, CPA" Date: Fri, 6 Dec 2024 20:09:22 +0800 Subject: [PATCH] Fix `iterator_to_array` to early return when `$preserveKeys` is false --- ...atorToArrayFunctionReturnTypeExtension.php | 27 ++++++++----------- .../Analyser/nsrt/iterator_to_array.php | 3 +++ 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/src/Type/Php/IteratorToArrayFunctionReturnTypeExtension.php b/src/Type/Php/IteratorToArrayFunctionReturnTypeExtension.php index 623e3c0bcd..d1dc17f176 100644 --- a/src/Type/Php/IteratorToArrayFunctionReturnTypeExtension.php +++ b/src/Type/Php/IteratorToArrayFunctionReturnTypeExtension.php @@ -31,33 +31,28 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection, } $traversableType = $scope->getType($arguments[0]->value); - $arrayKeyType = $traversableType->getIterableKeyType()->toArrayKey(); - - if ($arrayKeyType instanceof ErrorType) { - return new NeverType(true); - } - - $isList = false; if (isset($arguments[1])) { $preserveKeysType = $scope->getType($arguments[1]->value); if ($preserveKeysType->isFalse()->yes()) { - $arrayKeyType = new IntegerType(); - $isList = true; + return AccessoryArrayListType::intersectWith(new ArrayType( + new IntegerType(), + $traversableType->getIterableValueType(), + )); } } - $arrayType = new ArrayType( - $arrayKeyType, - $traversableType->getIterableValueType(), - ); + $arrayKeyType = $traversableType->getIterableKeyType()->toArrayKey(); - if ($isList) { - $arrayType = AccessoryArrayListType::intersectWith($arrayType); + if ($arrayKeyType instanceof ErrorType) { + return new NeverType(true); } - return $arrayType; + return new ArrayType( + $arrayKeyType, + $traversableType->getIterableValueType(), + ); } } diff --git a/tests/PHPStan/Analyser/nsrt/iterator_to_array.php b/tests/PHPStan/Analyser/nsrt/iterator_to_array.php index 4c7ddbc2b0..038b36f7fd 100644 --- a/tests/PHPStan/Analyser/nsrt/iterator_to_array.php +++ b/tests/PHPStan/Analyser/nsrt/iterator_to_array.php @@ -49,7 +49,9 @@ public function testBehaviorOnGenerators(): void }; assertType('array<0|1|2|\'\', 1|2|3|4>', iterator_to_array($generator1())); + assertType('list<1|2|3|4>', iterator_to_array($generator1(), false)); assertType('array<0|1|\'\'|\'a\', 1|2|3|4>', iterator_to_array($generator2())); + assertType('list<1|2|3|4>', iterator_to_array($generator2(), false)); } public function testOnGeneratorsWithIllegalKeysForArray(): void @@ -60,5 +62,6 @@ public function testOnGeneratorsWithIllegalKeysForArray(): void }; assertType('*NEVER*', iterator_to_array($illegalGenerator())); + assertType('list<\'b\'|\'c\'>', iterator_to_array($illegalGenerator(), false)); } }