Skip to content

Commit 9298ddc

Browse files
staabmondrejmirtes
authored andcommitted
non-empty-array might be empty after array_keys() with filter
1 parent 9435151 commit 9298ddc

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

src/Type/Accessory/NonEmptyArrayType.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ public function unsetOffset(Type $offsetType): Type
161161

162162
public function getKeysArrayFiltered(Type $filterValueType, TrinaryLogic $strict): Type
163163
{
164-
return $this->getKeysArray();
164+
return new ErrorType();
165165
}
166166

167167
public function getKeysArray(): Type
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
3+
namespace Bug13377;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
function doFoo() {
8+
$array = random_array();
9+
10+
// removing this line prevents the unexpected behavior
11+
if(empty($array)){
12+
return;
13+
}
14+
15+
// this should not assume result is not empty
16+
// same result when $strict is set to true
17+
$possiblyEmptyInvalid = array_keys($array, 'yes');
18+
assertType('list<(int|string)>', $possiblyEmptyInvalid);
19+
20+
$possiblyEmptyInvalid = array_keys($array, 'yes', true);
21+
assertType('list<(int|string)>', $possiblyEmptyInvalid);
22+
23+
$possiblyEmptyValid = array_keys(array_filter($array, fn($val) => $val == 'yes'));
24+
assertType('list<(int|string)>', $possiblyEmptyValid);
25+
}
26+
27+
28+
29+
/**
30+
* @return array<string>
31+
*/
32+
function random_array(): array
33+
{
34+
$return = [];
35+
for($i = 0; $i < 10; $i++){
36+
if(random_int(0, 1) === 1){
37+
$return[] = 'yes';
38+
}else{
39+
$return[] = 'no';
40+
}
41+
}
42+
43+
return $return;
44+
}

0 commit comments

Comments
 (0)