Skip to content

Commit da0d636

Browse files
committed
Implement the Text exporter.
1 parent 1b1b02e commit da0d636

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php
2+
3+
declare(strict_types = 1);
4+
5+
namespace spec\drupol\phptree\Exporter;
6+
7+
use drupol\phptree\Exporter\Text;
8+
use drupol\phptree\Node\ValueNode;
9+
use PhpSpec\ObjectBehavior;
10+
11+
class TextSpec extends ObjectBehavior
12+
{
13+
public function it_is_initializable()
14+
{
15+
$this->shouldHaveType(Text::class);
16+
}
17+
18+
public function it_can_export_to_text()
19+
{
20+
$tree = new ValueNode('root', 2);
21+
22+
$this
23+
->export($tree)
24+
->shouldReturn('[root]');
25+
26+
$nodes = [];
27+
foreach (\range('A', 'J') as $value) {
28+
$nodes[$value] = new ValueNode($value);
29+
}
30+
31+
$tree->add(...\array_values($nodes));
32+
33+
$this
34+
->export($tree)
35+
->shouldReturn('[root [A [C [G] [H]] [D [I] [J]]] [B [E] [F]]]');
36+
}
37+
}

src/Exporter/Text.php

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
3+
declare(strict_types = 1);
4+
5+
namespace drupol\phptree\Exporter;
6+
7+
use drupol\phptree\Node\ValueNodeInterface;
8+
9+
/**
10+
* Class Text
11+
*/
12+
class Text implements ExporterInterface
13+
{
14+
/**
15+
* Export the node in a string.
16+
*
17+
* @param \drupol\phptree\Node\ValueNodeInterface $node
18+
* The node.
19+
*
20+
* @return string
21+
* The string.
22+
*/
23+
public function export(ValueNodeInterface $node): string
24+
{
25+
$children = [];
26+
/** @var ValueNodeInterface $child */
27+
foreach ($node->children() as $child) {
28+
$children[] = $this->export($child);
29+
}
30+
31+
return [] === $children ?
32+
\sprintf('[%s]', $node->getValue()):
33+
\sprintf('[%s %s]', $node->getValue(), \implode(' ', $children));
34+
}
35+
}

0 commit comments

Comments
 (0)