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

Infer key-of constant array based on array_key_exists check #1830

Closed
bdsl opened this issue Jun 21, 2019 · 2 comments
Closed

Infer key-of constant array based on array_key_exists check #1830

bdsl opened this issue Jun 21, 2019 · 2 comments
Labels

Comments

@bdsl
Copy link
Contributor

bdsl commented Jun 21, 2019

I would like the following code to be valid. Currently Psalm emits ArgumentTypeCoercion - 28:31 - Argument 1 of foo::dogetdayname expects int(1)|int(2)|int(3)|int(4)|int(5)|int(6)|int(7), parent type int provided

<?php
  
class foo
{
  /** @var array<int,string> */
  public const DAYS = [
    1 => 'mon',
    2 => 'tue',
    3 => 'wed',
    4 => 'thu',
    5 => 'fri',
    6 => 'sat',
    7 => 'sun'
  ];
  
  /** @param key-of<self::DAYS> $dayNum*/
  private static function doGetDayName(int $dayNum): string
  {
    return self::DAYS[$dayNum];
  }
  
  /** @throws LogicException */
  public static function getDayName(int $dayNum): string
  {
    if (! array_key_exists($dayNum, self::DAYS)) {
      throw new \LogicException();
    }
    return self::doGetDayName($dayNum); // ArgumentTypeCoercion emitted here
  }
}

https://psalm.dev/r/8afe8ba4ea

For now we can work around this by adding /** @var key-of<self::DAYS> $dayNum */ (https://psalm.dev/r/7cc1f58d92 )

@muglug muglug added the bug label Jun 21, 2019
@weirdan
Copy link
Collaborator

weirdan commented Jun 21, 2019

Related: #942

@muglug muglug closed this as completed in 2fc7f5f Nov 10, 2019
@bdsl
Copy link
Contributor Author

bdsl commented Nov 12, 2019

Fixed in release 3.6.5

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

No branches or pull requests

3 participants