Completed
Push — master ( d6425f...46570e )
by Colin
15s queued 10s
created

NodeWalker::resumeAt()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
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 2031
    public function __construct(Node $root)
26
    {
27 2031
        $this->root = $root;
28 2031
        $this->current = $this->root;
29 2031
        $this->entering = true;
30 2031
    }
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 2031
    public function next(): ?NodeWalkerEvent
40
    {
41 2031
        $current = $this->current;
42 2031
        $entering = $this->entering;
43 2031
        if (null === $current) {
44 2031
            return null;
45
        }
46
47 2031
        if ($entering && $current->isContainer()) {
48 2031
            if ($current->firstChild()) {
49 2025
                $this->current = $current->firstChild();
50 2025
                $this->entering = true;
51
            } else {
52 2031
                $this->entering = false;
53
            }
54 2031
        } elseif ($current === $this->root) {
55 2031
            $this->current = null;
56 2025
        } elseif (null === $current->next()) {
57 2025
            $this->current = $current->parent();
58 2025
            $this->entering = false;
59
        } else {
60 1335
            $this->current = $current->next();
61 1335
            $this->entering = true;
62
        }
63
64 2031
        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 417
    public function resumeAt(Node $node, bool $entering = true)
74
    {
75 417
        $this->current = $node;
76 417
        $this->entering = $entering;
77 417
    }
78
}
79