Tree::getRootNode()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 6
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Remorhaz\UniLex\AST;
6
7
use Remorhaz\UniLex\Exception;
8
9
class Tree
10
{
11
    private $nextNodeId = 1;
12
13
    /**
14
     * @var Node[]
15
     */
16
    private $nodeMap = [];
17
18
    private $rootNodeId;
19
20
    public function createNode(string $name, int $id = null): Node
21
    {
22
        $node = new Node($id ?? $this->getNextNodeId(), $name);
23
        $this->nodeMap[$node->getId()] = $node;
24
        return $node;
25
    }
26
27
    /**
28
     * @param int $id
29
     * @return Node
30
     * @throws Exception
31
     */
32
    public function getNode(int $id): Node
33
    {
34
        if (!isset($this->nodeMap[$id])) {
35
            throw new Exception("Node {$id} is not defined in syntax tree");
36
        }
37
        return $this->nodeMap[$id];
38
    }
39
40
    /**
41
     * @param Node $node
42
     * @throws Exception
43
     */
44
    public function setRootNode(Node $node): void
45
    {
46
        if (isset($this->rootNodeId)) {
47
            throw new Exception("Root node of syntax tree is already set");
48
        }
49
        $this->rootNodeId = $node->getId();
50
    }
51
52
    /**
53
     * @return Node
54
     * @throws Exception
55
     */
56
    public function getRootNode(): Node
57
    {
58
        if (!isset($this->rootNodeId)) {
59
            throw new Exception("Root node of syntax tree is undefined");
60
        }
61
        return $this->getNode($this->rootNodeId);
62
    }
63
64
    private function getNextNodeId(): int
65
    {
66
        return $this->nextNodeId++;
67
    }
68
}
69