phpstan icon indicating copy to clipboard operation
phpstan copied to clipboard

Union of arrays is not array of unions

Open hemberger opened this issue 2 years ago • 7 comments

Bug report

If a parameter accepts a union of arrays, e.g. array<int>|array<string>, then I would expect a warning if I pass it an array of unions, e.g. array<int|string>.

My apologies if I'm missing something obvious here!

Code snippet that reproduces the problem

/**
 * @param array<string>|array<int> $array
 */
function test(array $array): void {}

$array = ['a', 2, 'c'];
test($array);

https://phpstan.org/r/e5262488-c506-4e6e-a46d-822b423c3e4e

Expected output

I was expecting something along the lines of:

Parameter #1 $array of function test expects array<string>|array<int>, array<int, int|string> given.

Did PHPStan help you today? Did it make you happy in any way?

Recently I've been using PHPStan with the phpstan-dba extension to safely modernize SQL calls in a really old library, and it's been very helpful!

hemberger avatar Feb 26 '23 08:02 hemberger

This would make https://github.com/phpstan/phpstan/issues/8918 possible, thank you!

mvorisek avatar Feb 26 '23 11:02 mvorisek

Can we mark this as a bug instead of a feature? I get that from a PHPStan perspective it might never have been supported, however from the perspective of set theory it's simply incorrect.

A hacky workaround that could work in some cases is to type one of the lists as an iterable: https://phpstan.org/r/8d20795d-2668-429e-99e3-cfde58513f01

SamMousa avatar Jun 19 '23 15:06 SamMousa

repro of non-intersecting keys: https://phpstan.org/r/42cf6794-8eea-4b08-afa7-95a05cc67479

mvorisek avatar Jan 29 '24 11:01 mvorisek

@hemberger After the latest push in 1.11.x, PHPStan now reports different result with your code snippet:

@@ @@
-No errors
+6: Function test() returns void but does not have any side effects.
Full report
Line Error
6 Function test() returns void but does not have any side effects.

phpstan-bot avatar Mar 29 '24 10:03 phpstan-bot

@SamMousa After the latest push in 1.11.x, PHPStan now reports different result with your code snippet:

@@ @@
+6: Function test() returns void but does not have any side effects.
 7: Dumped type: list<int>|iterable<string>
Full report
Line Error
6 Function test() returns void but does not have any side effects.
7 `Dumped type: list

phpstan-bot avatar Mar 29 '24 10:03 phpstan-bot