Completed
Push — master ( 5d9a5d...e6d18b )
by Chris
02:53
created

NodeListIterator   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Test Coverage

Coverage 64.29%

Importance

Changes 0
Metric Value
wmc 13
dl 0
loc 76
ccs 18
cts 28
cp 0.6429
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A next() 0 4 2
A rewind() 0 5 1
A notifyActivityStateChange() 0 10 3
A __destruct() 0 3 1
A current() 0 3 1
A __construct() 0 4 1
A valid() 0 9 2
A key() 0 5 2
1
<?php declare(strict_types=1);
2
3
namespace DaveRandom\Jom;
4
5
final class NodeListIterator implements \Iterator
6
{
7
    public const INACTIVE = -1;
8
    public const ACTIVE = 1;
9
10
    /** @var Node|null */
11
    private $firstNode;
12
13
    /** @var callable|null */
14
    private $activityStateChangeNotifier;
15
16
    /** @var int */
17
    private $activityState = self::INACTIVE;
18
19
    /** @var Node|null */
20
    private $currentNode;
21
22 2
    public function __construct(?Node $firstNode, callable $activityStateChangeNotifier = null)
23
    {
24 2
        $this->firstNode = $firstNode;
25 2
        $this->activityStateChangeNotifier = $activityStateChangeNotifier;
26
    }
27
28 2
    private function notifyActivityStateChange(int $newState): void
29
    {
30 2
        if ($this->activityState === $newState) {
31
            return;
32
        }
33
34 2
        $this->activityState = $newState;
35
36 2
        if ($this->activityStateChangeNotifier !== null) {
37 2
            ($this->activityStateChangeNotifier)($this->activityState);
38
        }
39
    }
40
41 2
    public function __destruct()
42
    {
43 2
        $this->notifyActivityStateChange(self::INACTIVE);
44
    }
45
46 2
    public function current(): ?Node
47
    {
48 2
        return $this->currentNode;
49
    }
50
51
    public function next(): void
52
    {
53
        if ($this->currentNode !== null) {
54
            $this->currentNode = $this->currentNode->getNextSibling();
55
        }
56
    }
57
58
    public function key()
59
    {
60
        return $this->currentNode !== null
61
            ? $this->currentNode->getKey()
62
            : null;
63
    }
64
65 2
    public function valid(): bool
66
    {
67 2
        if ($this->currentNode !== null) {
68 2
            return true;
69
        }
70
71
        $this->notifyActivityStateChange(self::INACTIVE);
72
73
        return false;
74
    }
75
76 2
    public function rewind(): void
77
    {
78 2
        $this->notifyActivityStateChange(self::ACTIVE);
79
80 2
        $this->currentNode = $this->firstNode;
81
    }
82
}
83