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

NodeListIterator::__destruct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
c 0
b 0
f 0
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 1
nc 1
nop 0
crap 1
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