Skip to content

Commit

Permalink
Tree::link disciplined
Browse files Browse the repository at this point in the history
minor edge-case issue corrected
  • Loading branch information
dakujem committed Feb 4, 2024
1 parent 961e051 commit 1391d6e
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 3 deletions.
8 changes: 6 additions & 2 deletions src/Tree.php
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,12 @@ private static function adoptChild(
string|int|null $key = null
): void {
$existing = $parent->childKey($child);
if (null !== $existing && $parent->child($existing) === $child) {
// Already linked.
if (
null !== $existing &&
$parent->child($existing) === $child &&
(null === $key || $existing === $key)
) {
// Already linked (with the same key or key not important).
return;
}
$parent->addChild($child, $key);
Expand Down
56 changes: 55 additions & 1 deletion tests/tree.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,60 @@ require_once __DIR__ . '/setup.php';
})();

(function () {
//
$node = new Node(null, parent: $parent = new Node(null));

Assert::same($parent, $node->parent());
Assert::same([], $parent->children());

Tree::link($node, $parent);
Assert::same($parent, $node->parent());
Assert::same([$node], $parent->children());
})();

(function () {
$parent = new Node(null, children: [
$node = new Node(null),
]);

Assert::same(null, $node->parent());
Assert::same([$node], $parent->children());

Tree::link($node, $parent);
Assert::same($parent, $node->parent());
Assert::same([$node], $parent->children());
})();

(function () {
$proxy = new NodeBuilder(fn(mixed $data) => new Node($data));

$parent = $proxy->node(null, [
'original' => $node = new Node(null),
]);

Assert::same($parent, $node->parent());
Assert::same(['original' => $node], $parent->children());

Tree::link($node, $parent, 'new-key');
Assert::same($parent, $node->parent());
Assert::same(['new-key' => $node], $parent->children());
})();

(function () {
$proxy = new NodeBuilder(fn(mixed $data) => new Node($data));

$parent = $proxy->node(null, [
'original' => $node = new Node(null),
]);

Assert::same($parent, $node->parent());
Assert::same(['original' => $node], $parent->children());

Tree::link($node, $parent, 'original');
Assert::same($parent, $node->parent());
Assert::same(['original' => $node], $parent->children());

Tree::link($node, $parent);
Assert::same($parent, $node->parent());
Assert::same(['original' => $node], $parent->children());
})();

0 comments on commit 1391d6e

Please sign in to comment.