From b18405e99f5e0ee25cbd58272f7c678b8a40057e Mon Sep 17 00:00:00 2001 From: Eric Lippmann Date: Tue, 10 Feb 2015 17:00:47 +0100 Subject: [PATCH] lib: Add SimpleTree Simple tree implementation for TreeNodes. refs #6630 --- library/Icinga/Data/Tree/SimpleTree.php | 90 +++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 library/Icinga/Data/Tree/SimpleTree.php diff --git a/library/Icinga/Data/Tree/SimpleTree.php b/library/Icinga/Data/Tree/SimpleTree.php new file mode 100644 index 000000000..46a91135d --- /dev/null +++ b/library/Icinga/Data/Tree/SimpleTree.php @@ -0,0 +1,90 @@ +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]; + } + + /** + * {@inheritdoc} + * @return TreeNodeIterator + */ + public function getIterator() + { + return new TreeNodeIterator($this->sentinel); + } +}