Skip to content

Commit 6f217f1

Browse files
committed
Fix return type of array_reverse() with $preserve_keys = true for lists
1 parent bbd64a9 commit 6f217f1

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/Type/Php/ArrayReverseFunctionReturnTypeExtension.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
use PhpParser\Node\Expr\FuncCall;
66
use PHPStan\Analyser\Scope;
77
use PHPStan\Reflection\FunctionReflection;
8+
use PHPStan\Type\Accessory\NonEmptyArrayType;
9+
use PHPStan\Type\ArrayType;
810
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
911
use PHPStan\Type\NeverType;
1012
use PHPStan\Type\Type;
@@ -43,6 +45,16 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
4345
return TypeCombinator::union(...$results);
4446
}
4547

48+
if ($preserveKeys) {
49+
// Remove list
50+
$newArrayType = new ArrayType($type->getIterableKeyType(), $type->getIterableValueType());
51+
if ($type->isIterableAtLeastOnce()->yes()) {
52+
$newArrayType = TypeCombinator::intersect($newArrayType, new NonEmptyArrayType());
53+
}
54+
55+
return $newArrayType;
56+
}
57+
4658
return $type;
4759
}
4860

tests/PHPStan/Analyser/nsrt/array-reverse.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,17 @@ public function constantArrays(array $a, array $b): void
4646
assertType('array{\'bar\', \'foo\'}|array{bar: 19, foo: 17}', array_reverse($b));
4747
assertType('array{19: \'bar\', 17: \'foo\'}|array{bar: 19, foo: 17}', array_reverse($b, true));
4848
}
49+
50+
/**
51+
* @param list<string> $a
52+
* @param non-empty-list<string> $b
53+
*/
54+
public function list(array $a, array $b): void
55+
{
56+
assertType('list<string>', array_reverse($a));
57+
assertType('array<int<0, max>, string>', array_reverse($a, true));
58+
59+
assertType('non-empty-list<string>', array_reverse($b));
60+
assertType('non-empty-array<int<0, max>, string>', array_reverse($b, true));
61+
}
4962
}

0 commit comments

Comments
 (0)