10
10
/**
11
11
* Class NaryNode.
12
12
*/
13
- class NaryNode extends Node
13
+ class NaryNode extends Node implements NaryNodeInterface
14
14
{
15
15
/**
16
16
* 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
53
53
public function add (NodeInterface ...$ nodes ): NodeInterface
54
54
{
55
55
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
+ }
59
75
}
60
76
61
77
return $ this ;
@@ -72,32 +88,8 @@ public function capacity(): int
72
88
/**
73
89
* {@inheritdoc}
74
90
*/
75
- public function getTraverser ()
91
+ public function getTraverser (): TraverserInterface
76
92
{
77
93
return $ this ->traverser ;
78
94
}
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
- }
103
95
}
0 commit comments