Skip to content

Commit

Permalink
Add an array exporter and the tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Dec 20, 2018
1 parent c99db23 commit ba0b0b6
Show file tree
Hide file tree
Showing 2 changed files with 110 additions and 0 deletions.
81 changes: 81 additions & 0 deletions spec/drupol/phptree/Exporter/SimpleArraySpec.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

declare(strict_types = 1);

namespace spec\drupol\phptree\Exporter;

use drupol\phptree\Exporter\SimpleArray;
use drupol\phptree\Node\ValueNode;
use PhpSpec\ObjectBehavior;

class SimpleArraySpec extends ObjectBehavior
{
public function it_is_initializable()
{
$this->shouldHaveType(SimpleArray::class);
}

public function it_can_export_to_an_array()
{
$tree = new ValueNode('root', 2);

$this
->export($tree)
->shouldReturn(['value' => 'root']);

$nodes = [];
foreach (\range('A', 'J') as $value) {
$nodes[$value] = new ValueNode($value);
}

$tree->add(...\array_values($nodes));

$return = [
'value' => 'root',
'children' => [
0 => [
'value' => 'A',
'children' => [
0 => [
'value' => 'C',
'children' => [
0 => [
'value' => 'G',
],
1 => [
'value' => 'H',
],
],
],
1 => [
'value' => 'D',
'children' => [
0 => [
'value' => 'I',
],
1 => [
'value' => 'J',
],
],
],
],
],
1 => [
'value' => 'B',
'children' => [
0 => [
'value' => 'E',
],
1 => [
'value' => 'F',
],
],
],
],
];

$this
->export($tree)
->shouldReturn($return);
}
}
29 changes: 29 additions & 0 deletions src/Exporter/SimpleArray.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types = 1);

namespace drupol\phptree\Exporter;

use drupol\phptree\Node\ValueNodeInterface;

/**
* Class SimpleArray
*/
class SimpleArray implements ExporterInterface
{
/**
* {@inheritdoc}
*/
public function export(ValueNodeInterface $node)
{
$children = [];
/** @var ValueNodeInterface $child */
foreach ($node->children() as $child) {
$children[] = $this->export($child);
}

return [] === $children ?
['value' => $node->getValue()]:
['value' => $node->getValue(), 'children' => $children];
}
}

0 comments on commit ba0b0b6

Please sign in to comment.