Skip to content

Commit 300c9d0

Browse files
phpstan-botclaude
andcommitted
Skip narrowing for non-constant arrays with multiple possible value types
For non-constant arrays like `non-empty-array<'a'|'b'>`, we cannot guarantee any specific value is present, so no narrowing should occur in the false context. Only narrow when the value type has exactly one finite type (e.g. `non-empty-array<'a'>`). Added regression test for this case. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent eafd010 commit 300c9d0

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

src/Type/Php/InArrayFunctionTypeSpecifyingExtension.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,10 @@ private function computeNeedleNarrowingType(TypeSpecifierContext $context, Type
203203
: new NeverType();
204204
}
205205
} else {
206-
$innerValueTypes[] = $array->getIterableValueType();
206+
$valueType = $array->getIterableValueType();
207+
if (count($valueType->getFiniteTypes()) === 1) {
208+
$innerValueTypes[] = $valueType;
209+
}
207210
}
208211
}
209212

tests/PHPStan/Analyser/nsrt/bug-14407.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,3 +86,15 @@ function testUnionWithOptionalKeys($x, $a): void
8686
assertType("'a'|'b'|'c'", $x);
8787
}
8888
};
89+
90+
/**
91+
* @param 'a'|'b'|'c' $x
92+
* @param non-empty-array<'a'|'b'> $a
93+
*/
94+
function testNonConstantArray($x, $a): void
95+
{
96+
assertType("non-empty-array<'a'|'b'>", $a);
97+
if (!\in_array($x, $a, true)) {
98+
assertType("'a'|'b'|'c'", $x);
99+
}
100+
};

0 commit comments

Comments
 (0)