Skip to content

Commit

Permalink
simple node builder added
Browse files Browse the repository at this point in the history
  • Loading branch information
dakujem committed Jan 18, 2024
1 parent ac9d6c4 commit 5a5bea0
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 4 deletions.
51 changes: 51 additions & 0 deletions src/Simple/NodeBuilder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

declare(strict_types=1);

namespace Dakujem\Oliva\Simple;

use Dakujem\Oliva\MovableNodeContract;
use Dakujem\Oliva\TreeNodeContract;
use LogicException;

/**
* A trivial builder that ensures the children are bound to the respective parent.
*
* @author Andrej Rypak <[email protected]>
*/
class NodeBuilder
{
/** @var callable */
private $factory;

public function __construct(
callable $node,
) {
$this->factory = $node;
}

public function node(mixed $data, iterable $children = []): TreeNodeContract
{
// Build the node.
$node = ($this->factory)($data);

// Check for consistency.
if (!$node instanceof MovableNodeContract) {
// TODO improve exceptions
throw new LogicException('The node factory must return a movable node instance.');
}

// Bind the children.
foreach ($children as $key => $child) {
// Check for consistency.
if (!$child instanceof MovableNodeContract) {
// TODO improve exceptions
throw new LogicException('The children must be movable node instances.');
}
$child->setParent($node);
$node->addChild($child, $key);
}

return $node;
}
}
8 changes: 4 additions & 4 deletions src/Simple/TreeBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

/**
* Simple tree builder.
* Wraps data that is already structured into tree node classes.
* Wraps data that is already structured as a tree into tree node classes.
*
* @author Andrej Rypak <[email protected]>
*/
Expand All @@ -21,14 +21,14 @@ public function build(
callable $node,
callable $children,
): TreeNodeContract {
return $this->buildNode(
return $this->wrapNode(
data: $data,
nodeFactory: $node,
childrenExtractor: $children,
);
}

public function buildNode(
private function wrapNode(
mixed $data,
callable $nodeFactory,
callable $childrenExtractor,
Expand All @@ -48,7 +48,7 @@ public function buildNode(
throw new LogicException('Children data extractor must return an iterable collection containing children data.');
}
foreach ($childrenData ?? [] as $key => $childData) {
$child = $this->buildNode(
$child = $this->wrapNode(
data: $childData,
nodeFactory: $nodeFactory,
childrenExtractor: $childrenExtractor,
Expand Down

0 comments on commit 5a5bea0

Please sign in to comment.