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
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\FuncCall\AddArrowFunctionParamArrayWhereDimFetchRector\Fixture;

final class SkipStringItems
{
/**
* @param array<int, string> $items
*/
public function run(array $items)
{
return array_map(fn ($item) => $item[0], $items);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\FuncCall\AddArrowFunctionParamArrayWhereDimFetchRector\Fixture;

final class SkipTemplateItems
{
/**
* @template T
* @param array<int, T> $items
*/
public function run(array $items)
{
return array_map(fn ($item) => $item['id'], $items);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use PhpParser\Node\Expr\Instanceof_;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Identifier;
use PHPStan\Type\Generic\TemplateType;
use PHPStan\Type\MixedType;
use PHPStan\Type\Type;
use Rector\PhpParser\Node\BetterNodeFinder;
Expand Down Expand Up @@ -98,7 +99,7 @@ public function refactor(Node $node): ?Node

// the items type does not change per closure param, resolve it once
$type = $this->getType($closureItems);
if ($this->hasMaybeObjectItems($type)) {
if ($this->hasNonArrayItems($type)) {
continue;
}

Expand Down Expand Up @@ -214,19 +215,20 @@ private function resolveInstanceofVariables(Closure|ArrowFunction $closureExpr):
}

/**
* Items that can be objects, e.g. ArrayAccess, must not be typed as array
* Items that are not always arrays, e.g. ArrayAccess, string or template, must not be typed as array
*/
private function hasMaybeObjectItems(Type $type): bool
private function hasNonArrayItems(Type $type): bool
{
if (! $type->isArray()->yes()) {
return false;
}

$itemType = $type->getIterableValueType();
if ($itemType instanceof MixedType) {
// unknown items are typed as before, except templates that can be anything
if ($itemType instanceof MixedType && ! $itemType instanceof TemplateType) {
return false;
}

return ! $itemType->isObject()->no();
return ! $itemType->isArray()->yes();
}
}
Loading