0

Given this code (https://psalm.dev/r/156e52eb66):

<?php

function keys(): array
{
  return ['foo', 'bar'];
}

// no lines above can be changed

foreach (keys() as $k) {
  echo gettype($k);
}

how would one type it assuming the keys function is not under our control (in a different project) and it effectively returns an array of mixed (array<array-key, mixed>).

So, one may only change the loop and around it.

Is it even possible?

UPD: I reported https://github.com/vimeo/psalm/issues/2025

zerkms
  • 249,484
  • 69
  • 436
  • 539
  • 2
    I'm not sure I understand what you're trying to achieve? You want to know what type the different elements in the array is? – Qirel Aug 16 '19 at 05:12
  • The library method returns an array of values of type `mixed`, so every array value may be of any valid php type. Check the provided psalm link, the warning is what I need to fix. – zerkms Aug 16 '19 at 05:25

3 Answers3

1

If I get it right this might help you:

foreach (array_keys(keys()) as $k) {
 echo gettype(keys()[$k])."\n";
}
VSMent
  • 376
  • 4
  • 11
  • 1
    Oh boy. I must admit it type checks, but isn't it ugly as hell? Who would run something like that in production – zerkms Aug 16 '19 at 05:40
  • For sure it is). I would not run it in production but for this psalm case it works. – VSMent Aug 17 '19 at 13:33
  • 1
    Also check that I updated the question with a link to a bug report, and psalm dev team kind of agreed it should be improved. – zerkms Aug 18 '19 at 00:37
1

You could use for loop instead of foreach loop to fix the warning.

$keys = keys();
for( $i = 0; $i < count( $keys); $i++ ) {
  echo gettype( $keys[$i] );
}

Here is the link in Psalm https://psalm.dev/r/20c1cbab73

ascsoftw
  • 3,466
  • 2
  • 15
  • 23
0

It's a bug of psalm.

Refer to Github: INFO: MixedAssignment - Cannot assign to a mixed type | when using string array key #1281,

And it has been fixed by muglug in this commit 6033345694727d7c3cf84adc76507c3785ed0295

LF00
  • 27,015
  • 29
  • 156
  • 295