psalm: DocblockTypeContradiction detecting string[]|string as only array

It doesn’t matter if I do @param string[]|string $fields or @param string|string[] $fields, it always gets detected as array<array-key, string>

https://psalm.dev/r/f472932324

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 16 (6 by maintainers)

Most upvoted comments

The docblock is only suggestive

The friction here is that this is fundamentally not how Psalm treats docblocks - if you put some type information in there it’ll treat it as truth.

This error is correct. At the place where you check !is_array it’s always an array already.

line 7/8 you check if it’s string, and assign it to an array (string[] specifically).

I found these snippets:

https://psalm.dev/r/f472932324
<?php
    /**
     * @param string[]|string $fields
     */
    function addWhere($fields): void
    {
        if (is_string($fields)) {
            $fields = [$fields];
        }

        if (! is_array($fields)) {
            throw new InvalidArgumentException('$field must be a string or array.');
        }
    }
Psalm output (using commit b46fb14):

ERROR: DocblockTypeContradiction - 11:15 - Docblock-defined type array<array-key, string> for $fields is always array<array-key, mixed>