Skip to content
This repository was archived by the owner on Dec 28, 2023. It is now read-only.

Commit 7d36a64

Browse files
committed
Merge pull request #2 from emonkak/fix-generator-exception-throwing
Avoid "Cannot rewind a generator that was already run" Exception
2 parents 363e30f + 1520504 commit 7d36a64

File tree

2 files changed

+41
-8
lines changed

2 files changed

+41
-8
lines changed

src/Iterator/LazyIterator.php

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,41 @@
44

55
use Emonkak\Collection\Utils\Iterators;
66

7-
class LazyIterator implements \IteratorAggregate
7+
class LazyIterator implements \Iterator
88
{
99
private $factory;
1010

11+
private $it;
12+
1113
public function __construct(callable $factory)
1214
{
1315
$this->factory = $factory;
1416
}
1517

16-
public function getIterator()
18+
public function current()
19+
{
20+
return $this->it->current();
21+
}
22+
23+
public function key()
24+
{
25+
return $this->it->key();
26+
}
27+
28+
public function next()
29+
{
30+
$this->it->next();
31+
}
32+
33+
public function rewind()
1734
{
1835
$factory = $this->factory;
19-
return Iterators::create($factory());
36+
$this->it = Iterators::create($factory());
37+
$this->it->rewind();
38+
}
39+
40+
public function valid()
41+
{
42+
return $this->it->valid();
2043
}
2144
}

tests/AbstractCollectionTest.php

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@ public function setUp()
1616
Collection::setDefaultProvider($this->getCollectionProvider());
1717
}
1818

19+
public function tearDown()
20+
{
21+
Collection::setDefaultProvider($this->defaultProvider);
22+
}
23+
1924
public function testFrom()
2025
{
2126
$it = new \EmptyIterator();
@@ -60,11 +65,6 @@ public function testCombineThrowsInvalidArgumentException()
6065
Collection::combine(1);
6166
}
6267

63-
public function tearDown()
64-
{
65-
Collection::setDefaultProvider($this->defaultProvider);
66-
}
67-
6868
public function testRange()
6969
{
7070
$result = Collection::range(0)->toList();
@@ -110,6 +110,16 @@ public function testRepeat()
110110
$this->assertEmpty($result);
111111
}
112112

113+
/**
114+
* @dataProvider provideCollectionFactory
115+
*/
116+
public function testGetIterator($factory)
117+
{
118+
$xs = $factory([1, 2, 3])->map(function($x) { return $x * 2; })->getIterator();
119+
$this->assertSame([2, 4, 6], iterator_to_array($xs));
120+
$this->assertSame([2, 4, 6], iterator_to_array($xs));
121+
}
122+
113123
/**
114124
* @dataProvider provideCollectionFactory
115125
*/

0 commit comments

Comments
 (0)