|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace BenTools\IterableFunctions; |
| 6 | + |
| 7 | +use Iterator; |
| 8 | +use IteratorIterator; |
| 9 | +use Traversable; |
| 10 | + |
| 11 | +/** |
| 12 | + * @internal |
| 13 | + * |
| 14 | + * @template TKey |
| 15 | + * @template TValue |
| 16 | + * |
| 17 | + * @implements Iterator<int, array<TKey, TValue>> |
| 18 | + */ |
| 19 | +final class ChunkIterator implements Iterator |
| 20 | +{ |
| 21 | + /** @var Iterator<TKey, TValue> */ |
| 22 | + private Iterator $iterator; |
| 23 | + |
| 24 | + private int $chunkSize; |
| 25 | + |
| 26 | + private bool $preserveKeys; |
| 27 | + |
| 28 | + private int $chunkIndex = 0; |
| 29 | + |
| 30 | + /** @var array<TKey, TValue> */ |
| 31 | + private array $buffer = []; |
| 32 | + |
| 33 | + /** |
| 34 | + * @param Traversable<TKey, TValue> $iterator |
| 35 | + */ |
| 36 | + public function __construct( |
| 37 | + Traversable $iterator, |
| 38 | + int $chunkSize, |
| 39 | + bool $preserveKeys = false, |
| 40 | + ) { |
| 41 | + $this->iterator = $iterator instanceof Iterator ? $iterator : new IteratorIterator($iterator); |
| 42 | + $this->chunkSize = $chunkSize; |
| 43 | + $this->preserveKeys = $preserveKeys; |
| 44 | + } |
| 45 | + |
| 46 | + public function current(): mixed |
| 47 | + { |
| 48 | + return $this->buffer; |
| 49 | + } |
| 50 | + |
| 51 | + public function next(): void |
| 52 | + { |
| 53 | + $this->fill(); |
| 54 | + $this->chunkIndex++; |
| 55 | + } |
| 56 | + |
| 57 | + public function key(): int |
| 58 | + { |
| 59 | + return $this->chunkIndex; |
| 60 | + } |
| 61 | + |
| 62 | + public function valid(): bool |
| 63 | + { |
| 64 | + if ($this->chunkIndex === 0) { |
| 65 | + $this->fill(); |
| 66 | + } |
| 67 | + |
| 68 | + return $this->buffer !== []; |
| 69 | + } |
| 70 | + |
| 71 | + public function rewind(): void |
| 72 | + { |
| 73 | + $this->iterator->rewind(); |
| 74 | + $this->chunkIndex = 0; |
| 75 | + $this->buffer = []; |
| 76 | + } |
| 77 | + |
| 78 | + private function fill(): void |
| 79 | + { |
| 80 | + $this->buffer = []; |
| 81 | + $i = 0; |
| 82 | + while ($this->iterator->valid() && $i++ < $this->chunkSize) { |
| 83 | + $current = $this->iterator->current(); |
| 84 | + |
| 85 | + if ($this->preserveKeys) { |
| 86 | + $this->buffer[$this->iterator->key()] = $current; |
| 87 | + } else { |
| 88 | + $this->buffer[] = $current; |
| 89 | + } |
| 90 | + |
| 91 | + $this->iterator->next(); |
| 92 | + } |
| 93 | + } |
| 94 | +} |
0 commit comments