Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix iterator_to_array to early return when $preserveKeys is false #3713

Merged
merged 1 commit into from
Dec 9, 2024
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
27 changes: 11 additions & 16 deletions src/Type/Php/IteratorToArrayFunctionReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
);
}

}
3 changes: 3 additions & 0 deletions tests/PHPStan/Analyser/nsrt/iterator_to_array.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -60,5 +62,6 @@ public function testOnGeneratorsWithIllegalKeysForArray(): void
};

assertType('*NEVER*', iterator_to_array($illegalGenerator()));
assertType('list<\'b\'|\'c\'>', iterator_to_array($illegalGenerator(), false));
}
}
Loading