phpstan-src icon indicating copy to clipboard operation
phpstan-src copied to clipboard

When an array of replacements is passed to `strtr()` it should be an associative array of strings

Open johnbillion opened this issue 3 years ago • 3 comments

This specifies the type of the replacements array to prevent accidental mistakes with the format of the array.

Refs:

  • https://phpstan.org/r/43f08118-c4d2-46aa-b05e-3a5c1c9bc4e3
  • https://3v4l.org/XXcWD

johnbillion avatar Dec 09 '22 16:12 johnbillion

This won't be valid anymore https://3v4l.org/UOOL0

But I think we can assume it's not a real use case, and people should use

[ '0' => 'e', '1' => 'u' ] 

instead

VincentLanglet avatar Dec 09 '22 17:12 VincentLanglet

That's a pretty wild use case. Is that something you've seen before?

johnbillion avatar Dec 09 '22 17:12 johnbillion

That's a pretty wild use case. Is that something you've seen before?

No, I just preferred to mention it.

I checked https://www.php.net/manual/en/function.strtr.php and it's said

The replace_pairs parameter may be used instead of to and from, in which case it's an array in the form array('from' => 'to', ...).

So [ 'e', 'u' ] is not supposed to be supported by PHP.

VincentLanglet avatar Dec 09 '22 17:12 VincentLanglet

Thinking again about this PR, this will create false-positive @johnbillion

Since array like ['1' => 'u' ] are inferred as an array with integer keys (see https://phpstan.org/r/ee405b11-251f-4e03-83a6-4db613e4e55f), it will be reported with the change you propose.

So it will be impossible to replace a number by something else with strtr without a PHPStan error.

Unless a test prove I'm wrong I think this should be closed

VincentLanglet avatar Oct 21 '25 21:10 VincentLanglet