Skip to content

Commit 0aea23f

Browse files
committed
Convert non-empty-arrays resulting from array_filter() to non-nullable
1 parent b18c7e0 commit 0aea23f

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

src/Type/Php/ArrayFindFunctionReturnTypeExtension.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,10 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
3232
return null;
3333
}
3434

35-
$resultTypes = $scope->getType(new FuncCall(new Name('\array_filter'), $functionCall->getArgs()))->getArrays();
35+
$resultTypes = $scope->getType(new FuncCall(new Name('\array_filter'), $functionCall->getArgs()));
36+
$resultType = TypeCombinator::union(...array_map(fn ($type) => $type->getIterableValueType(), $resultTypes->getArrays()));
3637

37-
return TypeCombinator::union(new NullType(), ...array_map(fn ($type) => $type->getIterableValueType(), $resultTypes));
38+
return $resultTypes->isIterableAtLeastOnce()->yes() ? $resultType : TypeCombinator::addNull($resultType);
3839
}
3940

4041
}

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

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,14 @@ function array_find(array $array, callable $callback)
2424

2525
/**
2626
* @param array<mixed> $array
27+
* @param non-empty-array<mixed> $non_empty_array
2728
*/
28-
function testMixed(array $array, callable $callback): void
29+
function testMixed(array $array, array $non_empty_array, callable $callback): void
2930
{
3031
assertType('mixed', array_find($array, $callback));
3132
assertType('int|null', array_find($array, 'is_int'));
33+
assertType('mixed', array_find($non_empty_array, $callback));
34+
assertType('int|null', array_find($non_empty_array, 'is_int'));
3235
}
3336

3437
/**
@@ -37,7 +40,20 @@ function testMixed(array $array, callable $callback): void
3740
function testConstant(array $array, callable $callback): void
3841
{
3942
assertType("1|'foo'|DateTime|null", array_find($array, $callback));
40-
assertType("1|null", array_find($array, 'is_int'));
43+
assertType('1', array_find($array, 'is_int'));
44+
}
45+
46+
/**
47+
* @param array<int> $array
48+
* @param non-empty-array<int> $non_empty_array
49+
*/
50+
function testInt(array $array, array $non_empty_array, callable $callback): void
51+
{
52+
assertType('int|null', array_find($array, $callback));
53+
assertType('int|null', array_find($array, 'is_int'));
54+
assertType('int|null', array_find($non_empty_array, $callback));
55+
// should be 'int'
56+
assertType('int|null', array_find($non_empty_array, 'is_int'));
4157
}
4258

4359
}

0 commit comments

Comments
 (0)