Completed
Pull Request — master (#357)
by Colin
05:36 queued 04:04
created

NodeWalker::resumeAt()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 2
1
<?php
2
3
namespace League\CommonMark\Node;
4
5
class NodeWalker
6
{
7
    /**
8
     * @var Node
9
     */
10
    private $root;
11
12
    /**
13
     * @var Node|null
14
     */
15
    private $current;
16
17
    /**
18
     * @var bool
19
     */
20
    private $entering;
21
22
    /**
23
     * @param Node $root
24
     */
25 2028
    public function __construct(Node $root)
26
    {
27 2028
        $this->root = $root;
28 2028
        $this->current = $this->root;
29 2028
        $this->entering = true;
30 2028
    }
31
32
    /**
33
     * Returns an event which contains node and entering flag
34
     * (entering is true when we enter a Node from a parent or sibling,
35
     * and false when we reenter it from child)
36
     *
37
     * @return NodeWalkerEvent|null
38
     */
39 2028
    public function next(): ?NodeWalkerEvent
40
    {
41 2028
        $current = $this->current;
42 2028
        $entering = $this->entering;
43 2028
        if (null === $current) {
44 2028
            return null;
45
        }
46
47 2028
        if ($entering && $current->isContainer()) {
48 2028
            if ($current->firstChild()) {
49 2022
                $this->current = $current->firstChild();
50 2022
                $this->entering = true;
51
            } else {
52 2028
                $this->entering = false;
53
            }
54 2028
        } elseif ($current === $this->root) {
55 2028
            $this->current = null;
56 2022
        } elseif (null === $current->next()) {
57 2022
            $this->current = $current->parent();
58 2022
            $this->entering = false;
59
        } else {
60 522
            $this->current = $current->next();
61 522
            $this->entering = true;
62
        }
63
64 2028
        return new NodeWalkerEvent($current, $entering);
65
    }
66
67
    /**
68
     * Resets the iterator to resume at the specified node
69
     *
70
     * @param Node $node
71
     * @param bool $entering
72
     */
73
    public function resumeAt(Node $node, bool $entering = true)
74
    {
75
        $this->current = $node;
76
        $this->entering = $entering;
77
    }
78
}
79