Skip to content

Commit f75e510

Browse files
authored
[8.x] Allow lazy collection to be instantiated from a generator (#36738)
* Allow lazy collection to be instantiated from any iterable * Fix only allow generator, not all iterables
1 parent f53e966 commit f75e510

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

src/Illuminate/Collections/LazyCollection.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use ArrayIterator;
66
use Closure;
77
use DateTimeInterface;
8+
use Generator;
89
use Illuminate\Support\Traits\EnumeratesValues;
910
use Illuminate\Support\Traits\Macroable;
1011
use IteratorAggregate;
@@ -29,7 +30,7 @@ class LazyCollection implements Enumerable
2930
*/
3031
public function __construct($source = null)
3132
{
32-
if ($source instanceof Closure || $source instanceof self) {
33+
if ($source instanceof Closure || $source instanceof Generator || $source instanceof self) {
3334
$this->source = $source;
3435
} elseif (is_null($source)) {
3536
$this->source = static::empty();
@@ -1364,6 +1365,10 @@ public function count()
13641365
*/
13651366
protected function makeIterator($source)
13661367
{
1368+
if ($source instanceof Generator) {
1369+
return $source;
1370+
}
1371+
13671372
if ($source instanceof IteratorAggregate) {
13681373
return $source->getIterator();
13691374
}

tests/Support/SupportLazyCollectionTest.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,31 @@ public function testCanCreateCollectionFromClosure()
6969
], $data->all());
7070
}
7171

72+
public function testCanCreateCollectionFromGenerator()
73+
{
74+
$iterable = function () {
75+
yield 1;
76+
yield 2;
77+
yield 3;
78+
};
79+
$data = LazyCollection::make($iterable());
80+
81+
$this->assertSame([1, 2, 3], $data->all());
82+
83+
$iterable = function () {
84+
yield 'a' => 1;
85+
yield 'b' => 2;
86+
yield 'c' => 3;
87+
};
88+
$data = LazyCollection::make($iterable());
89+
90+
$this->assertSame([
91+
'a' => 1,
92+
'b' => 2,
93+
'c' => 3,
94+
], $data->all());
95+
}
96+
7297
public function testEager()
7398
{
7499
$source = [1, 2, 3, 4, 5];

0 commit comments

Comments
 (0)