NodeListIterator::notifyActivityStateChange()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 10
c 0
b 0
f 0
ccs 5
cts 6
cp 0.8333
rs 10
cc 3
nc 3
nop 1
crap 3.0416
1
<?php declare(strict_types=1);
2
3
namespace DaveRandom\Jom;
4
5
use DaveRandom\Jom\Exceptions\CloneForbiddenException;
6
7
final class NodeListIterator implements \Iterator
8
{
9
    public const INACTIVE = -1;
10
    public const ACTIVE = 1;
11
12
    /** @var Node|null */
13
    private $firstNode;
14
15
    /** @var callable|null */
16
    private $activityStateChangeNotifier;
17
18
    /** @var int */
19
    private $activityState = self::INACTIVE;
20
21
    /** @var Node|null */
22
    private $currentNode;
23
24 9
    public function __construct(?Node $firstNode, ?callable $activityStateChangeNotifier = null)
25
    {
26 9
        $this->firstNode = $firstNode;
27 9
        $this->activityStateChangeNotifier = $activityStateChangeNotifier;
28
    }
29
30
    /**
31
     * @throws CloneForbiddenException
32
     */
33
    public function __clone()
34
    {
35
        throw new CloneForbiddenException(self::class . ' instance cannot be cloned');
36
    }
37
38 9
    private function notifyActivityStateChange(int $newState): void
39
    {
40 9
        if ($this->activityState === $newState) {
41
            return;
42
        }
43
44 9
        $this->activityState = $newState;
45
46 9
        if ($this->activityStateChangeNotifier !== null) {
47 9
            ($this->activityStateChangeNotifier)($this->activityState);
48
        }
49
    }
50
51 9
    public function __destruct()
52
    {
53 9
        $this->notifyActivityStateChange(self::INACTIVE);
54
    }
55
56 9
    public function current(): ?Node
57
    {
58 9
        return $this->currentNode;
59
    }
60
61
    public function next(): void
62
    {
63
        if ($this->currentNode !== null) {
64
            $this->currentNode = $this->currentNode->getNextSibling();
65
        }
66
    }
67
68
    public function key()
69
    {
70
        return $this->currentNode !== null
71
            ? $this->currentNode->getKey()
72
            : null;
73
    }
74
75 9
    public function valid(): bool
76
    {
77 9
        if ($this->currentNode !== null) {
78 9
            return true;
79
        }
80
81
        $this->notifyActivityStateChange(self::INACTIVE);
82
83
        return false;
84
    }
85
86 9
    public function rewind(): void
87
    {
88 9
        $this->notifyActivityStateChange(self::ACTIVE);
89
90 9
        $this->currentNode = $this->firstNode;
91
    }
92
}
93