Skip to content

Commit

Permalink
iterator_to_array must always return array-key (#5400)
Browse files Browse the repository at this point in the history
  • Loading branch information
orklah authored Mar 16, 2021
1 parent 1a3ff56 commit ff5a6cb
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
namespace Psalm\Internal\Provider\ReturnTypeProvider;

use Psalm\Plugin\EventHandler\Event\FunctionReturnTypeProviderEvent;
use Psalm\Type\Atomic\TTemplateParam;
use function array_shift;
use function assert;
use PhpParser;
use Psalm\Internal\Analyzer\Statements\Block\ForeachAnalyzer;
use Psalm\Internal\Type\Comparator\AtomicTypeComparator;
use Psalm\Internal\Codebase\InternalCallMapHandler;
Expand Down Expand Up @@ -86,6 +87,15 @@ public static function getFunctionReturnType(FunctionReturnTypeProviderEvent $ev
$key_type = Type::getArrayKey();
}

if ($key_type->isSingle() && $key_type->hasTemplate()) {
$template_types = $key_type->getTemplateTypes();
$template_type = array_shift($template_types);
if ($template_type->as->hasMixed()) {
$template_type->as = Type::getArrayKey();
$key_type = new Type\Union([$template_type]);
}
}

return new Type\Union([
new Type\Atomic\TArray([
$key_type,
Expand Down
13 changes: 13 additions & 0 deletions tests/Php71Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,19 @@ function foo(iterable $i): array {
return $i;
}',
],
'iterator_to_arrayMixedKey' => [
'<?php
/**
* @template TKey
* @template TValue
* @param Traversable<TKey, TValue> $traversable
* @return array<TValue>
*/
function toArray(Traversable $traversable): array
{
return iterator_to_array($traversable);
}',
],
'noReservedWordInDocblock' => [
'<?php
/**
Expand Down

0 comments on commit ff5a6cb

Please sign in to comment.