From 9e6ab0bf5d52b5b144e186c68bd60bd0f8305b97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Franti=C5=A1ek=20Ma=C5=A1a?= Date: Sun, 27 May 2018 11:43:53 +0200 Subject: [PATCH] Add array_filter support for union of arrays --- .../ArrayFilterFunctionReturnTypeReturnTypeExtension.php | 7 +++++-- tests/PHPStan/Analyser/NodeScopeResolverTest.php | 4 ++++ tests/PHPStan/Analyser/data/array-functions.php | 5 +++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/Type/Php/ArrayFilterFunctionReturnTypeReturnTypeExtension.php b/src/Type/Php/ArrayFilterFunctionReturnTypeReturnTypeExtension.php index fe1fb6304a..c4a4fa329a 100644 --- a/src/Type/Php/ArrayFilterFunctionReturnTypeReturnTypeExtension.php +++ b/src/Type/Php/ArrayFilterFunctionReturnTypeReturnTypeExtension.php @@ -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 @@ -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) { @@ -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(), diff --git a/tests/PHPStan/Analyser/NodeScopeResolverTest.php b/tests/PHPStan/Analyser/NodeScopeResolverTest.php index c07f669443..37056d0815 100644 --- a/tests/PHPStan/Analyser/NodeScopeResolverTest.php +++ b/tests/PHPStan/Analyser/NodeScopeResolverTest.php @@ -4140,6 +4140,10 @@ public function dataArrayFunctions(): array 'array', 'array_filter($withFalsey)', ], + [ + 'array(\'a\' => 1)', + 'array_filter($union)', + ], ]; } diff --git a/tests/PHPStan/Analyser/data/array-functions.php b/tests/PHPStan/Analyser/data/array-functions.php index 8bd993d80b..3dddf23370 100644 --- a/tests/PHPStan/Analyser/data/array-functions.php +++ b/tests/PHPStan/Analyser/data/array-functions.php @@ -51,6 +51,11 @@ /** @var array $withFalsey */ $withFalsey = doFoo(); +$union = ['a' => 1]; +if (rand(0, 1) === 1) { + $union['b'] = false; +} + /** @var array $generalStringKeys */ $generalStringKeys = doFoo();