1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the league/commonmark package. |
5
|
|
|
* |
6
|
|
|
* (c) Colin O'Dell <[email protected]> |
7
|
|
|
* |
8
|
|
|
* Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) |
9
|
|
|
* - (c) John MacFarlane |
10
|
|
|
* |
11
|
|
|
* For the full copyright and license information, please view the LICENSE |
12
|
|
|
* file that was distributed with this source code. |
13
|
|
|
*/ |
14
|
|
|
|
15
|
|
|
namespace League\CommonMark\Node; |
16
|
|
|
|
17
|
|
|
final class NodeWalker |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @var Node |
21
|
|
|
*/ |
22
|
|
|
private $root; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var Node|null |
26
|
|
|
*/ |
27
|
|
|
private $current; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var bool |
31
|
|
|
*/ |
32
|
|
|
private $entering; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param Node $root |
36
|
|
|
*/ |
37
|
2469 |
|
public function __construct(Node $root) |
38
|
|
|
{ |
39
|
2469 |
|
$this->root = $root; |
40
|
2469 |
|
$this->current = $this->root; |
41
|
2469 |
|
$this->entering = true; |
42
|
2469 |
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Returns an event which contains node and entering flag |
46
|
|
|
* (entering is true when we enter a Node from a parent or sibling, |
47
|
|
|
* and false when we reenter it from child) |
48
|
|
|
* |
49
|
|
|
* @return NodeWalkerEvent|null |
50
|
|
|
*/ |
51
|
2469 |
|
public function next(): ?NodeWalkerEvent |
52
|
|
|
{ |
53
|
2469 |
|
$current = $this->current; |
54
|
2469 |
|
$entering = $this->entering; |
55
|
2469 |
|
if (null === $current) { |
56
|
2466 |
|
return null; |
57
|
|
|
} |
58
|
|
|
|
59
|
2469 |
|
if ($entering && $current->isContainer()) { |
60
|
2466 |
|
if ($current->firstChild()) { |
61
|
2457 |
|
$this->current = $current->firstChild(); |
62
|
2457 |
|
$this->entering = true; |
63
|
|
|
} else { |
64
|
2466 |
|
$this->entering = false; |
65
|
|
|
} |
66
|
2469 |
|
} elseif ($current === $this->root) { |
67
|
2466 |
|
$this->current = null; |
68
|
2457 |
|
} elseif (null === $current->next()) { |
69
|
2457 |
|
$this->current = $current->parent(); |
70
|
2457 |
|
$this->entering = false; |
71
|
|
|
} else { |
72
|
678 |
|
$this->current = $current->next(); |
73
|
678 |
|
$this->entering = true; |
74
|
|
|
} |
75
|
|
|
|
76
|
2469 |
|
return new NodeWalkerEvent($current, $entering); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* Resets the iterator to resume at the specified node |
81
|
|
|
* |
82
|
|
|
* @param Node $node |
83
|
|
|
* @param bool $entering |
84
|
|
|
*/ |
85
|
3 |
|
public function resumeAt(Node $node, bool $entering = true) |
86
|
|
|
{ |
87
|
3 |
|
$this->current = $node; |
88
|
3 |
|
$this->entering = $entering; |
89
|
3 |
|
} |
90
|
|
|
} |
91
|
|
|
|