Skip to content

Commit

Permalink
Generalize filtered array with maybe falsey values
Browse files Browse the repository at this point in the history
  • Loading branch information
fmasa authored and ondrejmirtes committed Jun 18, 2018
1 parent 9e6ab0b commit 941684d
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/Type/Php/ArrayFilterFunctionReturnTypeReturnTypeExtension.php
Expand Up @@ -84,15 +84,22 @@ public function removeFalsey(Type $type): Type
$keys = $type->getKeyTypes();
$values = $type->getValueTypes();

$generalize = false;

foreach ($values as $offset => $value) {
if (!$falseyTypes->isSuperTypeOf($value)->yes()) {
continue;
}
$isFalsey = $falseyTypes->isSuperTypeOf($value);

unset($keys[$offset], $values[$offset]);
if ($isFalsey->yes()) {
unset($keys[$offset], $values[$offset]);
} elseif ($isFalsey->maybe()) {
$values[$offset] = TypeCombinator::remove($values[$offset], $falseyTypes);
$generalize = true;
}
}

return new ConstantArrayType(array_values($keys), array_values($values));
$filteredArray = new ConstantArrayType(array_values($keys), array_values($values));

return $generalize ? $filteredArray->generalize() : $filteredArray;
}

$keyType = $type->getIterableKeyType();
Expand Down
4 changes: 4 additions & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Expand Up @@ -4144,6 +4144,10 @@ public function dataArrayFunctions(): array
'array(\'a\' => 1)',
'array_filter($union)',
],
[
'array<int, int|true>',
'array_filter($withPossiblyFalsey)',
],
];
}

Expand Down
7 changes: 7 additions & 0 deletions tests/PHPStan/Analyser/data/array-functions.php
Expand Up @@ -56,6 +56,13 @@
$union['b'] = false;
}

/** @var bool $bool */
$bool = doFoo();
/** @var int $integer */
$integer = doFoo();

$withPossiblyFalsey = [$bool, $integer, '', 'a' => 0];

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

Expand Down

0 comments on commit 941684d

Please sign in to comment.