'PHPStorm: correct PHPDoc for a Collection of Objects?

I'm using the PHPStorm IDE, and run into trouble when I run the code inspection.

I have a method which returns a collection of objects. The Collection itself is an object, which has its own methods, and implements the Traversable interface:

class Repository
{
    public function findByCustomer(Customer $user)
    {
        // ...
        return new Collection($orders);
    }
}

If I document findByUser() to return a Collection, the code inspection understands the methods on this object, but doesn't understand what objects the collection contains:

/**
 * @return Collection
 */
public function findByCustomer() { ... }

Method getTotal() not found in class Collection

If I document findByUser() to return a collection of Order objects, the code inspection now understands what's inside the collection, but not the methods on the Collection itself:

/**
 * @return Order[]
 */
public function findByCustomer() { ... }

Method slice() not found in class Order[]

Is there a way to specify both at the same time, something like Java's syntax?

/**
 * @return Collection<Order>
 */
public function findByCustomer() { ... }


Solution 1:[1]

You can combine them (both types) together. May not be ideal in some situations, but works and you may consider it better than manually specifying type via @var PHPDoc comment.

/** @return Collection|Order[] */

Solution 2:[2]

As MV1908 said, you can use generic collecions in PHPStorm since 2021.2. However, note that this is only possible for a custom collection class (that you created yourself) and Doctrine collection, see https://blog.jetbrains.com/phpstorm/2021/07/phpstorm-2021-2-release/

With the release of PHPStorm 2021.3 its now possible to use generics also for Laravel Collections (however only for Laravel 9). See https://blog.jetbrains.com/phpstorm/2021/12/phpstorm-2021-3-release/#support_for_future_laravel_collections

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LazyOne
Solution 2 Adam