Passed
Pull Request — master (#79)
by Max
04:58 queued 02:49
created

ArrayAddingIterator::from()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
cc 2
eloc 3
c 2
b 0
f 2
nc 2
nop 1
dl 0
loc 10
rs 10
1
<?php
2
3
namespace MaxGoryunov\SavingIterator\Src;
4
5
use Iterator;
6
7
/**
8
 * Adding iterator which stores values in an array.
9
 * @template TKey
10
 * @template TValue
11
 * @implements AddingIterator<TKey, TValue>
12
 */
13
final class ArrayAddingIterator implements AddingIterator
14
{
15
16
    /**
17
     * Ctor.
18
     * 
19
     * @phpstan-param array<TKey, TValue> $added
20
     * @param array $added added values.
21
     */
22
    public function __construct(
23
        /**
24
         * Added values.
25
         *
26
         * @var array
27
         */
28
        private array $added = []
29
    ) {
30
    }
31
32
    /**
33
     * {@inheritDoc}
34
     */
35
    public function from(Iterator $source): AddingIterator
36
    {
37
        /**
38
         * @todo #66:20min Add a decorator for AddingIterator which does not
39
         *  allow to add values if source is not valid.
40
         */
41
        if ($source->valid()) {
42
            $this->added[$source->key()] ??= $source->current();
43
        }
44
        return new self($this->added);
45
    }
46
47
    /**
48
     * {@inheritDoc}
49
     */
50
    public function current(): mixed
51
    {
52
        return current($this->added);
53
    }
54
55
    /**
56
     * {@inheritDoc}
57
     */
58
    public function key(): mixed
59
    {
60
        return key($this->added);
61
    }
62
63
    /**
64
     * {@inheritDoc}
65
     */
66
    public function next(): void
67
    {
68
        next($this->added);
69
    }
70
71
    /**
72
     * {@inheritDoc}
73
     */
74
    public function valid(): bool
75
    {
76
        return $this->key() !== null;
77
    }
78
79
    /**
80
     * {@inheritDoc}
81
     */
82
    public function rewind(): void
83
    {
84
        reset($this->added);
85
    }
86
}
87