Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/Type/Php/IteratorToArrayFunctionReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
use PHPStan\Type\Accessory\AccessoryArrayListType;
use PHPStan\Type\ArrayType;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\ErrorType;
use PHPStan\Type\IntegerType;
use PHPStan\Type\NeverType;
use PHPStan\Type\Type;
use function strtolower;

Expand All @@ -29,7 +31,12 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
}

$traversableType = $scope->getType($arguments[0]->value);
$arrayKeyType = $traversableType->getIterableKeyType();
$arrayKeyType = $traversableType->getIterableKeyType()->toArrayKey();

if ($arrayKeyType instanceof ErrorType) {
return new NeverType(true);
}

$isList = false;

if (isset($arguments[1])) {
Expand Down
30 changes: 30 additions & 0 deletions tests/PHPStan/Analyser/nsrt/iterator_to_array.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace IteratorToArray;

use stdClass;
use Traversable;
use function iterator_to_array;
use function PHPStan\Testing\assertType;
Expand Down Expand Up @@ -31,4 +32,33 @@ public function testNotPreservingKeys(Traversable $foo)
{
assertType('list<string>', iterator_to_array($foo, false));
}

public function testBehaviorOnGenerators(): void
{
$generator1 = static function (): iterable {
yield 0 => 1;
yield true => 2;
yield 2 => 3;
yield null => 4;
};
$generator2 = static function (): iterable {
yield 0 => 1;
yield 'a' => 2;
yield null => 3;
yield true => 4;
};

assertType('array<0|1|2|\'\', 1|2|3|4>', iterator_to_array($generator1()));
assertType('array<0|1|\'\'|\'a\', 1|2|3|4>', iterator_to_array($generator2()));
}

public function testOnGeneratorsWithIllegalKeysForArray(): void
{
$illegalGenerator = static function (): iterable {
yield 'a' => 'b';
yield new stdClass => 'c';
};

assertType('*NEVER*', iterator_to_array($illegalGenerator()));
}
}
Loading