Skip to content

Commit 98fcbea

Browse files
committed
Merge pull request #696
2 parents 32cfb9b + 964954e commit 98fcbea

File tree

2 files changed

+10
-27
lines changed

2 files changed

+10
-27
lines changed

src/Model/CachingIterator.php

Lines changed: 9 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@
1818
namespace MongoDB\Model;
1919

2020
use Countable;
21-
use Generator;
2221
use Iterator;
22+
use IteratorIterator;
2323
use Traversable;
2424
use function count;
2525
use function current;
@@ -41,7 +41,7 @@ class CachingIterator implements Countable, Iterator
4141
/** @var array */
4242
private $items = [];
4343

44-
/** @var Generator */
44+
/** @var IteratorIterator */
4545
private $iterator;
4646

4747
/** @var boolean */
@@ -61,7 +61,9 @@ class CachingIterator implements Countable, Iterator
6161
*/
6262
public function __construct(Traversable $traversable)
6363
{
64-
$this->iterator = $this->wrapTraversable($traversable);
64+
$this->iterator = new IteratorIterator($traversable);
65+
66+
$this->iterator->rewind();
6567
$this->storeCurrentItem();
6668
}
6769

@@ -101,8 +103,12 @@ public function key()
101103
public function next()
102104
{
103105
if (! $this->iteratorExhausted) {
106+
$this->iteratorAdvanced = true;
104107
$this->iterator->next();
108+
105109
$this->storeCurrentItem();
110+
111+
$this->iteratorExhausted = ! $this->iterator->valid();
106112
}
107113

108114
next($this->items);
@@ -156,20 +162,4 @@ private function storeCurrentItem()
156162

157163
$this->items[$key] = $this->iterator->current();
158164
}
159-
160-
/**
161-
* Wraps the Traversable with a Generator.
162-
*
163-
* @param Traversable $traversable
164-
* @return Generator
165-
*/
166-
private function wrapTraversable(Traversable $traversable)
167-
{
168-
foreach ($traversable as $key => $value) {
169-
yield $key => $value;
170-
$this->iteratorAdvanced = true;
171-
}
172-
173-
$this->iteratorExhausted = true;
174-
}
175165
}

tests/Model/CachingIteratorTest.php

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ public function testIterationWithEmptySet()
5353

5454
public function testPartialIterationDoesNotExhaust()
5555
{
56-
$traversable = $this->getTraversableThatThrows([1, 2, new Exception()]);
56+
$traversable = $this->getTraversable([1, 2, new Exception()]);
5757
$iterator = new CachingIterator($traversable);
5858

5959
$expectedKey = 0;
@@ -110,13 +110,6 @@ public function testCountWithEmptySet()
110110
}
111111

112112
private function getTraversable($items)
113-
{
114-
foreach ($items as $item) {
115-
yield $item;
116-
}
117-
}
118-
119-
private function getTraversableThatThrows($items)
120113
{
121114
foreach ($items as $item) {
122115
if ($item instanceof Exception) {

0 commit comments

Comments
 (0)