Skip to content

Commit

Permalink
Root methods
Browse files Browse the repository at this point in the history
  • Loading branch information
nicmart committed Mar 5, 2014
1 parent 1229dec commit 43007fb
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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'))
Expand Down
23 changes: 23 additions & 0 deletions src/Tree/Node/NodeTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -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}
*/
Expand Down
19 changes: 19 additions & 0 deletions tests/Tree/Node/NodeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
}

0 comments on commit 43007fb

Please sign in to comment.