1 | <?php |
||
24 | final class CachingIterator implements Iterator |
||
25 | { |
||
26 | /** @var array */ |
||
27 | private $items = []; |
||
28 | |||
29 | /** @var Generator|null */ |
||
30 | private $iterator; |
||
31 | |||
32 | /** @var bool */ |
||
33 | private $iteratorAdvanced = false; |
||
34 | |||
35 | /** @var bool */ |
||
36 | private $iteratorExhausted = false; |
||
37 | |||
38 | /** |
||
39 | * Initialize the iterator and stores the first item in the cache. This |
||
40 | * effectively rewinds the Traversable and the wrapping Generator, which |
||
41 | * will execute up to its first yield statement. Additionally, this mimics |
||
42 | * behavior of the SPL iterators and allows users to omit an explicit call |
||
43 | * to rewind() before using the other methods. |
||
44 | */ |
||
45 | 145 | public function __construct(Traversable $iterator) |
|
50 | |||
51 | 107 | public function __destruct() |
|
55 | |||
56 | 82 | public function toArray() : array |
|
62 | |||
63 | /** |
||
64 | * @see http://php.net/iterator.current |
||
65 | * |
||
66 | * @return mixed |
||
67 | */ |
||
68 | 91 | public function current() |
|
72 | |||
73 | /** |
||
74 | * @see http://php.net/iterator.mixed |
||
75 | * |
||
76 | * @return mixed |
||
77 | */ |
||
78 | 34 | public function key() |
|
82 | |||
83 | /** |
||
84 | * @see http://php.net/iterator.next |
||
85 | */ |
||
86 | 85 | public function next() : void |
|
95 | |||
96 | /** |
||
97 | * @see http://php.net/iterator.rewind |
||
98 | */ |
||
99 | 30 | public function rewind() : void |
|
110 | |||
111 | /** |
||
112 | * @see http://php.net/iterator.valid |
||
113 | */ |
||
114 | 34 | public function valid() : bool |
|
118 | |||
119 | /** |
||
120 | * Ensures that the inner iterator is fully consumed and cached. |
||
121 | */ |
||
122 | 86 | private function exhaustIterator() : void |
|
130 | |||
131 | 145 | private function getIterator() : Generator |
|
139 | |||
140 | /** |
||
141 | * Stores the current item in the cache. |
||
142 | */ |
||
143 | 145 | private function storeCurrentItem() : void |
|
153 | |||
154 | 145 | private function wrapTraversable(Traversable $traversable) : Generator |
|
163 | } |
||
164 |