Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[6.x] Add an eager() method to the lazy collection class #29832

Merged
merged 2 commits into from
Sep 25, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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