Skip to content

Commit

Permalink
[10.x] Uses @template-covariant in collections (laravel#46872)
Browse files Browse the repository at this point in the history
* docs: update collection docs to use template-covariant for the values

This allows developers to use classes with inheritance on collections. See types/Support/Collection.php for an example

* Revert `@template-covariant` on Arrayable

* Apply fixes from StyleCI

---------

Co-authored-by: rvanvelzen <rvanvelzen@swis.nl>
Co-authored-by: StyleCI Bot <bot@styleci.io>
  • Loading branch information
3 people committed Apr 24, 2023
1 parent 1793066 commit 2922575
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 4 deletions.
3 changes: 2 additions & 1 deletion src/Illuminate/Collections/Collection.php
Expand Up @@ -12,7 +12,8 @@

/**
* @template TKey of array-key
* @template TValue
*
* @template-covariant TValue
*
* @implements \ArrayAccess<TKey, TValue>
* @implements \Illuminate\Support\Enumerable<TKey, TValue>
Expand Down
3 changes: 2 additions & 1 deletion src/Illuminate/Collections/Enumerable.php
Expand Up @@ -12,7 +12,8 @@

/**
* @template TKey of array-key
* @template TValue
*
* @template-covariant TValue
*
* @extends \Illuminate\Contracts\Support\Arrayable<TKey, TValue>
* @extends \IteratorAggregate<TKey, TValue>
Expand Down
3 changes: 2 additions & 1 deletion src/Illuminate/Collections/LazyCollection.php
Expand Up @@ -16,7 +16,8 @@

/**
* @template TKey of array-key
* @template TValue
*
* @template-covariant TValue
*
* @implements \Illuminate\Support\Enumerable<TKey, TValue>
*/
Expand Down
3 changes: 2 additions & 1 deletion src/Illuminate/Collections/Traits/EnumeratesValues.php
Expand Up @@ -19,7 +19,8 @@

/**
* @template TKey of array-key
* @template TValue
*
* @template-covariant TValue
*
* @property-read HigherOrderCollectionProxy $average
* @property-read HigherOrderCollectionProxy $avg
Expand Down
42 changes: 42 additions & 0 deletions types/Support/Collection.php
Expand Up @@ -1055,3 +1055,45 @@ class CustomCollection extends Collection
assertType('int', $int);
assertType('User', $user);
}

class Animal
{
}
class Tiger extends Animal
{
}
class Lion extends Animal
{
}
class Zebra extends Animal
{
}

class Zoo
{
/**
* @var \Illuminate\Support\Collection<int, Animal>
*/
private Collection $animals;

public function __construct()
{
$this->animals = collect([
new Tiger,
new Lion,
new Zebra,
]);
}

/**
* @return \Illuminate\Support\Collection<int, Animal>
*/
public function getWithoutZebras(): Collection
{
return $this->animals->filter(fn (Animal $animal) => ! $animal instanceof Zebra);
}
}

$zoo = new Zoo();

assertType('Illuminate\Support\Collection<int, Animal>', $zoo->getWithoutZebras());

0 comments on commit 2922575

Please sign in to comment.