diff --git a/README.md b/README.md index 9879cda..7444e7d 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,7 @@ In Tree you can find a basic but flexible tree data structure for php together with and an handful Builder class, that enables you to build tree in a fluent way. ## Changelog + - 0.2.1 root() and isRoot() methods - 0.2.0 Dropped php 5.3 support. Node implemented as a trait. - 0.1.2 Added YieldVisitor, to get the yield of the tree - 0.1.1 Parent and neighbors methods (thanks to https://github.com/jdeniau) @@ -80,6 +81,11 @@ $root = (new Node('root')) $grandchild->getAncestors(); // Returns [$root, $child] ``` +### Getting the root of a node +```php +$root = $node->root(); +``` + ### Getting the neighbors of a node ```php $root = (new Node('root')) diff --git a/src/Tree/Node/NodeTrait.php b/src/Tree/Node/NodeTrait.php index d4b5044..12b8a15 100644 --- a/src/Tree/Node/NodeTrait.php +++ b/src/Tree/Node/NodeTrait.php @@ -177,6 +177,29 @@ public function isLeaf() return count($this->children) == 0; } + /** + * @return bool + */ + public function isRoot() + { + return $this->getParent() === null; + } + + /** + * Find the root of the node + * + * @return NodeInterface + */ + public function root() + { + $node = $this; + + while ($parent = $node->getParent()) + $node = $parent; + + return $node; + } + /** * {@inheritdoc} */ diff --git a/tests/Tree/Node/NodeTest.php b/tests/Tree/Node/NodeTest.php index 7972707..683cff9 100644 --- a/tests/Tree/Node/NodeTest.php +++ b/tests/Tree/Node/NodeTest.php @@ -150,4 +150,23 @@ public function testIsLeaf() $this->assertFalse($root->isLeaf()); } + + public function testRoot() + { + $root = (new Node('root')) + ->addChild( + (new Node('child'))->addChild($grandchild = new Node('grandchild')) + ); + + $this->assertSame($root, $grandchild->root()); + } + + public function testIsRoot() + { + $root = new Node('root'); + $root->addChild($child = new Node('child')); + + $this->assertTrue($root->isRoot()); + $this->assertFalse($child->isRoot()); + } } \ No newline at end of file