-
-
Notifications
You must be signed in to change notification settings - Fork 62
/
NodeBuilder.php
110 lines (86 loc) · 2.13 KB
/
NodeBuilder.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php
/**
* Copyright (c) 2013-2023 Nicolò Martini
*
* For the full copyright and license information, please view
* the LICENSE.md file that was distributed with this source code.
*
* @see https://github.com/nicmart/Tree
*/
namespace Tree\Builder;
use Tree\Node\Node;
use Tree\Node\NodeInterface;
/**
* Main implementation of the NodeBuilderInterface.
*/
class NodeBuilder implements NodeBuilderInterface
{
/**
* @var array<int, NodeInterface>
*/
private array $nodeStack = [];
public function __construct(?NodeInterface $node = null)
{
$this->setNode($node ?: $this->nodeInstanceByValue());
}
public function setNode(NodeInterface $node): static
{
$this
->emptyStack()
->pushNode($node);
return $this;
}
public function getNode(): NodeInterface
{
return $this->nodeStack[\count($this->nodeStack) - 1];
}
public function leaf(mixed $value = null): static
{
$this->getNode()->addChild(
$this->nodeInstanceByValue($value),
);
return $this;
}
public function leafs(mixed ...$values): static
{
foreach ($values as $value) {
$this->leaf($value);
}
return $this;
}
public function tree(mixed $value = null): static
{
$node = $this->nodeInstanceByValue($value);
$this->getNode()->addChild($node);
$this->pushNode($node);
return $this;
}
public function end(): ?static
{
$this->popNode();
return $this;
}
public function nodeInstanceByValue(mixed $value = null): NodeInterface
{
return new Node($value);
}
public function value(mixed $value): static
{
$this->getNode()->setValue($value);
return $this;
}
private function emptyStack(): static
{
$this->nodeStack = [];
return $this;
}
private function pushNode(NodeInterface $node): static
{
$this->nodeStack[] = $node;
return $this;
}
private function popNode(): void
{
\array_pop($this->nodeStack);
}
}