-
-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathMemoizingIterator.php
More file actions
77 lines (60 loc) · 1.3 KB
/
MemoizingIterator.php
File metadata and controls
77 lines (60 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Iterators;
/**
* MemoizingIterator wraps around another iterator and caches its keys and values during iteration.
* This allows the data to be re-iterated multiple times.
* @template K
* @template V
* @implements \Iterator<K, V>
*/
class MemoizingIterator implements \Iterator
{
private array $cache = [];
private int $index = 0;
/**
* @param \Iterator<K, V> $inner
*/
public function __construct(
private readonly \Iterator $inner,
) {
}
public function rewind(): void
{
if (!$this->cache) {
$this->inner->rewind();
}
$this->index = 0;
}
/**
* @return V
*/
public function current(): mixed
{
return $this->cache[$this->index][1] ?? null;
}
/**
* @return K
*/
public function key(): mixed
{
return $this->cache[$this->index][0] ?? null;
}
public function next(): void
{
if (!isset($this->cache[++$this->index])) {
$this->inner->next();
}
}
public function valid(): bool
{
if (!isset($this->cache[$this->index]) && $this->inner->valid()) {
$this->cache[$this->index] = [$this->inner->key(), $this->inner->current()];
}
return isset($this->cache[$this->index]);
}
}