Skip to content

Commit 760f86f

Browse files
authored
Fix array_filter with callback optional persistance
1 parent 7a93939 commit 760f86f

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

src/Type/Php/ArrayFilterFunctionReturnTypeReturnTypeExtension.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
use PHPStan\Type\TypeUtils;
3434
use function array_map;
3535
use function count;
36+
use function in_array;
3637
use function is_string;
3738
use function strtolower;
3839
use function substr;
@@ -192,9 +193,11 @@ private function filterByTruthyValue(Scope $scope, Error|Variable|null $itemVar,
192193
$results = [];
193194
foreach ($constantArrays as $constantArray) {
194195
$builder = ConstantArrayTypeBuilder::createEmpty();
196+
$optionalKeys = $constantArray->getOptionalKeys();
195197
foreach ($constantArray->getKeyTypes() as $i => $keyType) {
196198
$itemType = $constantArray->getValueTypes()[$i];
197199
[$newKeyType, $newItemType, $optional] = $this->processKeyAndItemType($scope, $keyType, $itemType, $itemVar, $keyVar, $expr);
200+
$optional = $optional || in_array($i, $optionalKeys, true);
198201
if ($newKeyType instanceof NeverType || $newItemType instanceof NeverType) {
199202
continue;
200203
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php
2+
3+
namespace Bug11570;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
/**
8+
* @param array{one?: string, two?: string|null, three: string|null} $data
9+
*/
10+
function test(array $data): void
11+
{
12+
$data = array_filter($data, fn($var) => $var !== null);
13+
assertType("array{one?: string, two?: string, three?: string}", $data);
14+
}

0 commit comments

Comments
 (0)