Skip to content

Fix always-true detection in in_array with union type haystack #3888

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 17, 2025

Conversation

sayuprc
Copy link
Contributor

@sayuprc sayuprc commented Mar 19, 2025

@staabm
Copy link
Contributor

staabm commented Mar 19, 2025

your PR has impact on more open bugs.

please look at the changes and decide whether these are correct/intended
https://github.com/phpstan/phpstan-src/actions/runs/13947226248?pr=3888

please add additional tests to cover this bugs, in case they are fixed

Comment on lines 22 to 41
/**
* @param array{
* key1: ?bool,
* } $myArray
*/
public function testBool(array $myArray): ?\stdClass
{
if (\in_array(null, $myArray, true)) {
return null;
}

return (object) $myArray;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you should test a case which is expected to still emit an error after the change (a array which always contains null)

@sayuprc sayuprc requested a review from staabm March 21, 2025 06:14
@@ -147,7 +147,7 @@ public function findSpecifiedType(
foreach ($haystackArrayTypes as $haystackArrayType) {
if ($haystackArrayType instanceof ConstantArrayType) {
foreach ($haystackArrayType->getValueTypes() as $i => $haystackArrayValueType) {
if ($haystackArrayType->isOptionalKey($i)) {
if ($haystackArrayValueType instanceof UnionType || $haystackArrayType->isOptionalKey($i)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe there's a better way to ask this. Something like count($haystackArrayValueType->getFiniteTypes()) === 1.

@sayuprc sayuprc requested a review from ondrejmirtes May 6, 2025 14:17
@ondrejmirtes
Copy link
Member

Please fix the conflicts.

@ondrejmirtes ondrejmirtes merged commit 3ac64db into phpstan:2.1.x Jul 17, 2025
401 of 419 checks passed
@ondrejmirtes
Copy link
Member

Thank you!

@sayuprc sayuprc deleted the resolve-12755 branch July 17, 2025 14:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Incorrect NarrowedType detection on in_array(null) and bool value
3 participants