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
|
|
|
|