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
16 changes: 10 additions & 6 deletions src/Type/Php/RangeFunctionReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,15 @@
use function abs;
use function count;
use function floor;
use function intdiv;
use function is_array;
use function is_finite;
use function is_numeric;
use function is_string;
use function max;
use function min;
use function range;
use const PHP_INT_MAX;

#[AutowiredService]
final class RangeFunctionReturnTypeExtension implements DynamicFunctionReturnTypeExtension
Expand Down Expand Up @@ -186,11 +188,13 @@ private static function getLongRangeType(
&& $endConstant instanceof ConstantIntegerType
&& $stepConstant instanceof ConstantIntegerType
) {
$low = min($startConstant->getValue(), $endConstant->getValue());
$high = max($startConstant->getValue(), $endConstant->getValue());

return self::getNonEmptyListOfType(
IntegerRangeType::fromInterval(
min($startConstant->getValue(), $endConstant->getValue()),
max($startConstant->getValue(), $endConstant->getValue()),
),
IntegerRangeType::fromInterval($low, $high),
// the keys stay unbounded when $high - $low overflows
$low >= 0 || $high <= PHP_INT_MAX + $low ? intdiv($high - $low, abs($stepConstant->getValue())) : null,
);
}

Expand All @@ -207,11 +211,11 @@ private static function getLongRangeType(
);
}

private static function getNonEmptyListOfType(Type $type): IntersectionType
private static function getNonEmptyListOfType(Type $type, ?int $maxKey = null): IntersectionType
{
return new IntersectionType([
new ArrayType(
IntegerRangeType::createAllGreaterThanOrEqualTo(0),
IntegerRangeType::fromInterval(0, $maxKey),
$type,
),
new NonEmptyArrayType(),
Expand Down
22 changes: 22 additions & 0 deletions tests/PHPStan/Analyser/nsrt/range-array-count-limit.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,25 @@ function doFoo(): void
assertType('non-empty-list<float>', range(0, 100000000, 0.5));
assertType('non-empty-list<int<0, 300>>', range(0, 300));
}

function keys(): void
{
foreach (range(0, 50) as $key => $value) {
assertType('int<0, 50>', $key);
}
foreach (range(10, 1000, 7) as $key => $value) {
assertType('int<0, 141>', $key);
}
foreach (range(1000, 10, -7) as $key => $value) {
assertType('int<0, 141>', $key);
}
foreach (range(0, -100000000) as $key => $value) {
assertType('int<0, 100000000>', $key);
}
foreach (range(0, 2000000000, 3) as $key => $value) {
assertType('int<0, 666666666>', $key);
}
foreach (range(PHP_INT_MIN, PHP_INT_MAX) as $key => $value) {
assertType('int<0, max>', $key);
}
}
Loading