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