Skip to content

Commit

Permalink
[6.x] Add an eager() method to the lazy collection class (laravel#2…
Browse files Browse the repository at this point in the history
…9832)

* Add a cache() method to the lazy collection class

* Rename `cache` method to `eager`
  • Loading branch information
JosephSilber authored and cangelis committed Sep 25, 2019
1 parent 9b20234 commit 53d7c19
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/Illuminate/Support/LazyCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,16 @@ public function all()
return iterator_to_array($this->getIterator());
}

/**
* Eager load all items into a new lazy collection backed by an array.
*
* @return static
*/
public function eager()
{
return new static($this->all());
}

/**
* Get the average value of a given key.
*
Expand Down
10 changes: 10 additions & 0 deletions tests/Support/SupportLazyCollectionIsLazyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,16 @@

class SupportLazyCollectionIsLazyTest extends TestCase
{
public function testEagerEnumeratesOnce()
{
$this->assertEnumeratesOnce(function ($collection) {
$collection = $collection->eager();

$collection->count();
$collection->all();
});
}

public function testChunkIsLazy()
{
$this->assertDoesNotEnumerate(function ($collection) {
Expand Down
13 changes: 13 additions & 0 deletions tests/Support/SupportLazyCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,19 @@ public function testCanCreateCollectionFromClosure()
], $data->all());
}

public function testEager()
{
$source = [1, 2, 3, 4, 5];

$data = LazyCollection::make(function () use (&$source) {
yield from $source;
})->eager();

$source[] = 6;

$this->assertSame([1, 2, 3, 4, 5], $data->all());
}

public function testTapEach()
{
$data = LazyCollection::times(10);
Expand Down

0 comments on commit 53d7c19

Please sign in to comment.