AbstractLoader::next()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

Changes 2
Bugs 2 Features 0
Metric Value
cc 4
eloc 5
c 2
b 2
f 0
nc 3
nop 0
dl 0
loc 11
ccs 5
cts 5
cp 1
crap 4
rs 10
1
<?php declare(strict_types=1);
2
3
namespace Jasny\Container\Loader;
4
5
/**
6
 * Base class for loader using two iterators.
7
 */
8
abstract class AbstractLoader implements \OuterIterator
9
{
10
    /**
11
     * @var \Iterator
12
     */
13
    protected $items;
14
15
    /**
16
     * @var \ArrayIterator|null
17
     */
18
    protected $entries;
19
20
21
    /**
22
     * Class constructor.
23
     *
24
     * @param \Iterator $items
25
     */
26 16
    public function __construct(\Iterator $items)
27
    {
28 16
        $this->items = $items;
29 16
        $this->prepareNext();
30 15
    }
31
32
    /**
33
     * Prepare new entries
34
     *
35
     * @return void
36
     */
37
    abstract protected function prepareNext(): void;
38
39
    /**
40
     * Return the current element
41
     *
42
     * @return callable|null
43
     */
44 11
    public function current(): ?callable
45
    {
46 11
        return isset($this->entries) ? $this->entries->current() : null;
47
    }
48
49
    /**
50
     * Move forward to next element
51
     *
52
     * @return void
53
     */
54 11
    public function next(): void
55
    {
56 11
        if (!isset($this->entries)) {
57
            // Shouldn't happen if `prepareNext()` works correctly
58
            return; // @codeCoverageIgnore
59
        }
60
61 11
        $this->entries->next();
62
63 11
        while (!$this->entries->valid() && $this->items->valid()) {
64 11
            $this->prepareNext();
65
        }
66 10
    }
67
68
    /**
69
     * Return the key of the current element
70
     *
71
     * @return string|null
72
     */
73 11
    public function key(): ?string
74
    {
75 11
        return isset($this->entries) ? (string)$this->entries->key() : null;
76
    }
77
78
    /**
79
     * Checks if current position is valid
80
     *
81
     * @return bool
82
     */
83 13
    public function valid(): bool
84
    {
85 13
        return isset($this->entries) && $this->entries->valid();
86
    }
87
88
    /**
89
     * Rewind the iterator to the first element
90
     *
91
     * @return void
92
     */
93 13
    public function rewind(): void
94
    {
95 13
        $this->items->rewind();
96 13
        $this->entries = null;
97
98 13
        $this->prepareNext();
99 13
    }
100
101
    /**
102
     * Returns the inner iterator for the current entry.
103
     *
104
     * @return \Iterator
105
     */
106 2
    public function getInnerIterator(): \Iterator
107
    {
108 2
        return $this->items;
109
    }
110
}
111