summaryrefslogtreecommitdiffstats
path: root/library/Icinga/Data/Tree/SimpleTree.php
blob: e89f58929368abe7294fbcf4f5c0e0cc796307ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
/* Icinga Web 2 | (c) 2015 Icinga Development Team | GPLv2+ */

namespace Icinga\Data\Tree;

use IteratorAggregate;
use LogicException;
use Traversable;

/**
 * A simple tree
 */
class SimpleTree implements IteratorAggregate
{
    /**
     * Root node
     *
     * @var TreeNode
     */
    protected $sentinel;

    /**
     * Nodes
     *
     * @var array
     */
    protected $nodes = array();

    /**
     * Create a new simple tree
     */
    public function __construct()
    {
        $this->sentinel = new TreeNode();
    }

    /**
     * Add a child node
     *
     * @param   TreeNode $child
     * @param   TreeNode $parent
     *
     * @return $this
     */
    public function addChild(TreeNode $child, TreeNode $parent = null)
    {
        if ($parent === null) {
            $parent = $this->sentinel;
        } elseif (! isset($this->nodes[$parent->getId()])) {
            throw new LogicException(sprintf(
                'Can\'t append child node %s to parent node %s: Parent node does not exist',
                $child->getId(),
                $parent->getId()
            ));
        }
        if (isset($this->nodes[$child->getId()])) {
            throw new LogicException(sprintf(
                'Can\'t append child node %s to parent node %s: Child node does already exist',
                $child->getId(),
                $parent->getId()
            ));
        }
        $this->nodes[$child->getId()] = $child;
        $parent->appendChild($child);
        return $this;
    }

    /**
     * Get a node by its ID
     *
     * @param   mixed   $id
     *
     * @return  TreeNode|null
     */
    public function getNode($id)
    {
        if (! isset($this->nodes[$id])) {
            return null;
        }
        return $this->nodes[$id];
    }

    /**
     * @return TreeNodeIterator
     */
    public function getIterator(): Traversable
    {
        return new TreeNodeIterator($this->sentinel);
    }
}