Skip to content

Commit 265d4be

Browse files
committed
Test duplicate node linking
Adds `Tree::link` method tests for various scenarios linking the same nodes multiple times.
1 parent a825923 commit 265d4be

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

tests/tree.phpt

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,3 +135,55 @@ require_once __DIR__ . '/setup.php';
135135
}, NodeNotMovable::class, 'Encountered a non-movable node while manipulating a tree.');
136136
})();
137137

138+
139+
(function () {
140+
//
141+
// Duplicate linking of the same node without specifying a key should have no effect.
142+
//
143+
144+
$parent = new Node(null);
145+
$node = new Node(null);
146+
147+
Tree::link($node, $parent); // default index `0`
148+
Tree::link($node, $parent); // has no effect
149+
Assert::same([0 => $node], $parent->children());
150+
151+
Tree::link($node, $parent, 'foo');
152+
Tree::link($node, $parent); // has no effect, preserves the previously assigned key
153+
Assert::same(['foo' => $node], $parent->children());
154+
})();
155+
156+
157+
(function () {
158+
//
159+
// Duplicate linking of the same node with the same key should have no effect.
160+
//
161+
162+
$node1 = new Node(null);
163+
$node2 = new Node(null);
164+
$children = ['one' => $node1, 'two' => $node2];
165+
$parent = new Node(null, children: $children);
166+
Assert::same($children, $parent->children()); // sanity check
167+
168+
// Calling Tree::link here has no effect and does not change the order of the child nodes.
169+
Tree::link($node1, $parent, 'one');
170+
Assert::same($children, $parent->children());
171+
})();
172+
173+
174+
(function () {
175+
//
176+
// Duplicate linking of the same node with a specific key should change the node's key (re-link the node with a different child key).
177+
//
178+
179+
$node1 = new Node(null);
180+
$node2 = new Node(null);
181+
$children = ['one' => $node1, 'two' => $node2];
182+
$parent = new Node(null, children: $children);
183+
Assert::same($children, $parent->children()); // sanity check
184+
185+
// This call removes the child and re-links it under a different key.
186+
Tree::link($node1, $parent, 'three');
187+
Assert::same(['two' => $node2, 'three' => $node1], $parent->children());
188+
})();
189+

0 commit comments

Comments
 (0)