Skip to content
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

array_flip and array_rand #6859

Closed
mj4444ru opened this issue Nov 8, 2021 · 4 comments · Fixed by #9651
Closed

array_flip and array_rand #6859

mj4444ru opened this issue Nov 8, 2021 · 4 comments · Fixed by #9651

Comments

@mj4444ru
Copy link

mj4444ru commented Nov 8, 2021

https://psalm.dev/r/b14406d8ed

How to fix it?

@psalm-github-bot
Copy link

I found these snippets:

https://psalm.dev/r/b14406d8ed
<?php
$specialChars = array_flip(['~', '!', '@', '#', ':', '$', '%', '^', '&', '*', '?']);
array_rand($specialChars, 2);
Psalm output (using commit 9491ea4):

ERROR: ArgumentTypeCoercion - 3:12 - Argument 1 of array_rand expects non-empty-array<array-key, mixed>, parent type array<"!"|"#"|"$"|"%"|"&"|"*"|":"|"?"|"@"|"^"|"~", 0|1|2|3|4|5|6|7|8|9|10> provided

@orklah
Copy link
Collaborator

orklah commented Nov 8, 2021

array_flip transform your array into array<array-key, array-key>, which is correct but not very precise.

For your need, you'd need array<"~"|"!"|"@"|"#"|":"|"$"|"%"|"^"|"&"|"*"|"?", int>. This can be done by adding a return type provider here: https://github.com/vimeo/psalm/tree/master/src/Psalm/Internal/Provider/ReturnTypeProvider

@weirdan
Copy link
Collaborator

weirdan commented Nov 8, 2021

I think it would be enough to update the stub like this:

diff --git a/stubs/CoreGenericFunctions.phpstub b/stubs/CoreGenericFunctions.phpstub
index e8b3026cf..802f7498d 100644
--- a/stubs/CoreGenericFunctions.phpstub
+++ b/stubs/CoreGenericFunctions.phpstub
@@ -123,7 +123,7 @@ function array_diff_assoc(array $array, array ...$arrays)
  *
  * @param array<TKey, TValue> $array
  *
- * @return array<TValue, TKey>
+ * @return ($array is non-empty-array ? non-empty-array<TValue, TKey> : array<TValue, TKey>)
  * @psalm-pure
  */

@orklah
Copy link
Collaborator

orklah commented Nov 8, 2021

Oh, it might indeed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants