| 1 | <?php |
||
| 18 | final class ChunkIterator implements Iterator |
||
| 19 | { |
||
| 20 | protected $iterator; |
||
| 21 | protected $size; |
||
| 22 | protected $chunk; |
||
| 23 | protected $position; |
||
| 24 | |||
| 25 | 6 | public function __construct(iterable $iterable, int $size = null) |
|
| 26 | { |
||
| 27 | 6 | if (is_array($iterable)) { |
|
| 28 | 5 | $iterable = new ArrayIterator($iterable); |
|
| 29 | } |
||
| 30 | |||
| 31 | 6 | $this->iterator = $iterable; |
|
| 32 | 6 | $this->size = $size ?? 1; |
|
| 33 | 6 | } |
|
| 34 | |||
| 35 | 4 | public function current() |
|
| 36 | { |
||
| 37 | 4 | return $this->chunk; |
|
| 38 | } |
||
| 39 | |||
| 40 | 6 | public function next() |
|
| 41 | { |
||
| 42 | 6 | $this->chunk = []; |
|
| 43 | 6 | $this->position++; |
|
| 44 | |||
| 45 | 6 | for ($i = 0; $i < $this->size && $this->iterator->valid(); $i++) { |
|
| 46 | 4 | $this->chunk[] = $this->iterator->current(); |
|
| 47 | 4 | $this->iterator->next(); |
|
| 48 | } |
||
| 49 | 6 | } |
|
| 50 | |||
| 51 | 4 | public function key() |
|
| 55 | |||
| 56 | 6 | public function valid() |
|
| 57 | { |
||
| 58 | 6 | return (bool)$this->chunk; |
|
| 60 | |||
| 61 | 6 | public function rewind() |
|
| 67 | } |
||
| 68 |