psalm: [MismatchingDocblockReturnType] I don't get how this works

class Foo {
  /** @var \stdClass[]|\ArrayObject */
  public $bar;
  
  /**
   * @return \stdClass[]|\ArrayObject
   */
  public function getBar(): \ArrayObject
  {
    return $this->bar;
  }
}

In real use case, this is a problem for Doctrine Collections, where docblock is specified like this

/**
 * @return RoomItem[]|Collection|Selectable
 */
public function getRoomItems(): Collection
{
    return $this->roomItems;
}

ERROR: MismatchingDocblockReturnType - src/Entity/Item.php:75:8 - Docblock has incorrect return type ‘Doctrine\Common\Collections\Collection<mixed, App\Entity\RoomItem>|Doctrine\Common\Collections\Selectable’, should be ‘Doctrine\Common\Collections\Collection’

If I change it to

/**
 * @return RoomItem[]|Collection
 */
public function getRoomItems(): Collection
{
    return $this->roomItems;
}

error is no longer shown, even though it’s pretty same like original example code

About this issue

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

Most upvoted comments

The website doesn’t have that config option (allowPhpStormGenerics="true") enabled because it’s terrible, and breaks the notion of union types.

Ok, so to make Psalm happy you’d need to change the docblock to

@param ArrayCollection<mixed, RoomItem>|PersistentCollection<mixed, RoomItem>

When I add support for intersection types in docblocks you’d use this instead:

@param Collection<mixed, RoomItem>&Selectable