1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace MaxGoryunov\SavingIterator\Src; |
4
|
|
|
|
5
|
|
|
use ArrayAccess; |
6
|
|
|
use Iterator; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Adding iterator which stores values in a user provided iterator. |
10
|
|
|
* @template TKey |
11
|
|
|
* @template TValue |
12
|
|
|
* @implements AddingIterator<TKey, TValue> |
13
|
|
|
*/ |
14
|
|
|
final class OpenAddingIterator implements AddingIterator |
15
|
|
|
{ |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Ctor. |
19
|
|
|
* |
20
|
|
|
* @phpstan-param Iterator<TKey, TValue>&ArrayAccess<TKey, TValue> $added |
21
|
|
|
* @param Iterator&ArrayAccess $added iterator with stored values. |
22
|
|
|
*/ |
23
|
|
|
public function __construct( |
24
|
|
|
/** |
25
|
|
|
* Iterator with stored values. |
26
|
|
|
* |
27
|
|
|
* @phpstan-var Iterator<TKey, TValue>&ArrayAccess<TKey, TValue> |
28
|
|
|
* @var Iterator&ArrayAccess |
29
|
|
|
*/ |
30
|
|
|
private Iterator|ArrayAccess $added |
31
|
|
|
) { |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* {@inheritDoc} |
36
|
|
|
*/ |
37
|
|
|
public function from(Iterator $source): AddingIterator |
38
|
|
|
{ |
39
|
|
|
/** |
40
|
|
|
* @todo #83:20min Cover that Iterator works with an immutable |
41
|
|
|
* iterator. |
42
|
|
|
*/ |
43
|
|
|
/** |
44
|
|
|
* @todo #83:20min Assert that iterator does not add values if they are already stored. |
45
|
|
|
*/ |
46
|
|
|
$updated = clone $this->added; |
47
|
|
|
$updated[$source->key()] ??= $source->current(); |
48
|
|
|
return new self($updated); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* {@inheritDoc} |
53
|
|
|
*/ |
54
|
|
|
public function current(): mixed |
55
|
|
|
{ |
56
|
|
|
return $this->added->current(); |
|
|
|
|
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* {@inheritDoc} |
61
|
|
|
*/ |
62
|
|
|
public function key(): mixed |
63
|
|
|
{ |
64
|
|
|
return $this->added->key(); |
|
|
|
|
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* {@inheritDoc} |
69
|
|
|
*/ |
70
|
|
|
public function next(): void |
71
|
|
|
{ |
72
|
|
|
$this->added->next(); |
|
|
|
|
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* {@inheritDoc} |
77
|
|
|
*/ |
78
|
|
|
public function valid(): bool |
79
|
|
|
{ |
80
|
|
|
return $this->added->valid(); |
|
|
|
|
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* {@inheritDoc} |
85
|
|
|
*/ |
86
|
|
|
public function rewind(): void |
87
|
|
|
{ |
88
|
|
|
/** |
89
|
|
|
* @todo #83:20min Assert that iterator rewinds original iterator. |
90
|
|
|
*/ |
91
|
|
|
$this->added->rewind(); |
|
|
|
|
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|