Skip to content

Commit

Permalink
Add new method NodeInterface::level() and its tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Dec 13, 2019
1 parent ebbb505 commit 7ffd252
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
32 changes: 32 additions & 0 deletions spec/drupol/phptree/Node/NodeSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,38 @@ public function it_can_use_withChildren(): void
->shouldYield(new ArrayIterator([]));
}

public function it_can_get_the_tree_levels(): void
{
$nodeLevel3_1 = new Node();
$nodeLevel3_2 = new Node();
$nodeLevel2 = new Node();
$nodeLevel1 = new Node();

$nodeLevel2->add($nodeLevel3_1, $nodeLevel3_2);
$nodeLevel1->add($nodeLevel2);
$this->add($nodeLevel1);

$this
->level(0)
->shouldYield([$this]);

$this
->level(1)
->shouldYield([$nodeLevel1]);

$this
->level(2)
->shouldYield([$nodeLevel2]);

$this
->level(3)
->shouldYield([$nodeLevel3_1, $nodeLevel3_2]);

$this
->level(4)
->shouldYield([]);
}

public function it_has_a_degree(): void
{
$this
Expand Down
13 changes: 13 additions & 0 deletions src/Node/Node.php
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,19 @@ public function isRoot(): bool
return null === $this->storage()->getParent();
}

/**
* {@inheritdoc}
*/
public function level(int $level): Traversable
{
/** @var \drupol\phptree\Node\NodeInterface $node */
foreach ($this->all() as $node) {
if ($node->depth() === $level) {
yield $node;
}
}
}

/**
* {@inheritdoc}
*/
Expand Down
7 changes: 7 additions & 0 deletions src/Node/NodeInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,13 @@ public function isLeaf(): bool;
*/
public function isRoot(): bool;

/**
* @param int $level
*
* @return Traversable<\drupol\phptree\Node\NodeInterface>
*/
public function level(int $level): Traversable;

/**
* Remove children.
*
Expand Down

0 comments on commit 7ffd252

Please sign in to comment.