Skip to content

Commit

Permalink
Add array_filter support for union of arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
fmasa authored and ondrejmirtes committed Jun 18, 2018
1 parent 6c4bbce commit 9e6ab0b
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use PHPStan\Type\NullType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeUtils;
use PHPStan\Type\UnionType;

class ArrayFilterFunctionReturnTypeReturnTypeExtension implements \PHPStan\Type\DynamicFunctionReturnTypeExtension
Expand All @@ -42,7 +43,9 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
$itemType = $arrayArgType->getIterableValueType();

if ($callbackArg === null) {
return $this->removeFalsey($arrayArgType);
return TypeCombinator::union(
...array_map([$this, 'removeFalsey'], TypeUtils::getArrays($arrayArgType))
);
}

if ($flagArg === null && $callbackArg instanceof Closure && count($callbackArg->stmts) === 1) {
Expand All @@ -66,7 +69,7 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
return new ArrayType($keyType, $itemType);
}

private function removeFalsey(Type $type): Type
public function removeFalsey(Type $type): Type
{
$falseyTypes = new UnionType([
new NullType(),
Expand Down
4 changes: 4 additions & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4140,6 +4140,10 @@ public function dataArrayFunctions(): array
'array<int, true>',
'array_filter($withFalsey)',
],
[
'array(\'a\' => 1)',
'array_filter($union)',
],
];
}

Expand Down
5 changes: 5 additions & 0 deletions tests/PHPStan/Analyser/data/array-functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@
/** @var array<int, bool|null> $withFalsey */
$withFalsey = doFoo();

$union = ['a' => 1];
if (rand(0, 1) === 1) {
$union['b'] = false;
}

/** @var array<string, int> $generalStringKeys */
$generalStringKeys = doFoo();

Expand Down

0 comments on commit 9e6ab0b

Please sign in to comment.