Skip to content

Commit 8f46d3c

Browse files
committed
Add the depth() method.
1 parent 72bb2ba commit 8f46d3c

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

spec/drupol/phptree/Node/NodeSpec.php

+28
Original file line numberDiff line numberDiff line change
@@ -202,4 +202,32 @@ public function it_can_use_withChildren()
202202
->children()
203203
->shouldReturn([]);
204204
}
205+
206+
public function it_can_get_its_depth()
207+
{
208+
$this
209+
->depth()
210+
->shouldReturn(0);
211+
212+
$tree = new \drupol\phptree\Node\ValueNode('root', 2);
213+
214+
$tree->add($this->getWrappedObject());
215+
216+
$this
217+
->depth()
218+
->shouldReturn(1);
219+
220+
$nodes = [];
221+
foreach (\range('A', 'Z') as $v) {
222+
$nodes[] = new \drupol\phptree\Node\ValueNode($v);
223+
}
224+
225+
$tree->add(...$nodes);
226+
227+
$tree->add($this->getWrappedObject());
228+
229+
$this
230+
->depth()
231+
->shouldReturn(4);
232+
}
205233
}

src/Node/Node.php

+8
Original file line numberDiff line numberDiff line change
@@ -174,4 +174,12 @@ public function withChildren(NodeInterface ...$nodes): NodeInterface
174174

175175
return $clone;
176176
}
177+
178+
/**
179+
* {@inheritdoc}
180+
*/
181+
public function depth(): int
182+
{
183+
return \count($this->getAncestors());
184+
}
177185
}

src/Node/NodeInterface.php

+8
Original file line numberDiff line numberDiff line change
@@ -97,4 +97,12 @@ public function getSibblings(): array;
9797
* The amound of children.
9898
*/
9999
public function degree(): int;
100+
101+
/**
102+
* Get the node depth from the root node.
103+
*
104+
* @return int
105+
* The depth is the number of nodes before root.
106+
*/
107+
public function depth(): int;
100108
}

0 commit comments

Comments
 (0)