Skip to content

Commit bb6e292

Browse files
committed
Update NaryNode - make it simpler and cleaner.
1 parent d8d70f7 commit bb6e292

File tree

1 file changed

+21
-29
lines changed

1 file changed

+21
-29
lines changed

src/Node/NaryNode.php

+21-29
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
/**
1111
* Class NaryNode.
1212
*/
13-
class NaryNode extends Node
13+
class NaryNode extends Node implements NaryNodeInterface
1414
{
1515
/**
1616
* The capacity of a node, the maximum children a node can have.
@@ -53,9 +53,25 @@ public function __construct(int $capacity = 0, NodeInterface $parent = null, Tra
5353
public function add(NodeInterface ...$nodes): NodeInterface
5454
{
5555
foreach ($nodes as $node) {
56-
/** @var \drupol\phptree\Node\Node $parent */
57-
$parent = $this->findFirstAvailableNode();
58-
$parent->storage['children'][] = $node->setParent($parent);
56+
if (0 === $this->capacity() || ($this->degree() < $this->capacity())) {
57+
parent::add($node);
58+
59+
continue;
60+
}
61+
62+
foreach ($this->traverser->traverse($this) as $candidate) {
63+
if (!($candidate instanceof NaryNodeInterface)) {
64+
continue;
65+
}
66+
67+
if ($candidate->degree() >= $candidate->capacity()) {
68+
continue;
69+
}
70+
71+
$candidate->add($node);
72+
73+
break;
74+
}
5975
}
6076

6177
return $this;
@@ -72,32 +88,8 @@ public function capacity(): int
7288
/**
7389
* {@inheritdoc}
7490
*/
75-
public function getTraverser()
91+
public function getTraverser(): TraverserInterface
7692
{
7793
return $this->traverser;
7894
}
79-
80-
/**
81-
* Find first node in the tree that could have a new children.
82-
*
83-
* @return \drupol\phptree\Node\NodeInterface
84-
*/
85-
private function findFirstAvailableNode(): NodeInterface
86-
{
87-
$capacity = $this->capacity();
88-
89-
foreach ($this->getTraverser()->traverse($this) as $node) {
90-
if (\method_exists($node, 'capacity')) {
91-
$capacity = $node->capacity();
92-
}
93-
94-
if ($node->degree() >= $capacity) {
95-
continue;
96-
}
97-
98-
return $node;
99-
}
100-
101-
return $this;
102-
}
10395
}

0 commit comments

Comments
 (0)