Skip to content

Commit 8a93bcd

Browse files
committed
Add an array importer and its tests.
1 parent fcbc3c1 commit 8a93bcd

File tree

2 files changed

+105
-0
lines changed

2 files changed

+105
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<?php
2+
3+
declare(strict_types = 1);
4+
5+
namespace spec\drupol\phptree\Importer;
6+
7+
use drupol\phptree\Importer\SimpleArray;
8+
use drupol\phptree\Node\NodeInterface;
9+
use PhpSpec\ObjectBehavior;
10+
11+
class SimpleArraySpec extends ObjectBehavior
12+
{
13+
public function it_is_initializable()
14+
{
15+
$this->shouldHaveType(SimpleArray::class);
16+
}
17+
18+
public function it_can_import()
19+
{
20+
$array = [
21+
'value' => 'root',
22+
'children' => [
23+
0 => [
24+
'value' => 'child1',
25+
],
26+
1 => [
27+
'value' => 'child2',
28+
],
29+
],
30+
];
31+
32+
$this
33+
->import($array)
34+
->shouldImplement(NodeInterface::class);
35+
36+
$this
37+
->import($array)
38+
->count()
39+
->shouldReturn(2);
40+
41+
$this
42+
->import($array)
43+
->isRoot()
44+
->shouldReturn(TRUE);
45+
}
46+
}

src/Importer/SimpleArray.php

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
<?php
2+
3+
declare(strict_types = 1);
4+
5+
namespace drupol\phptree\Importer;
6+
7+
use drupol\phptree\Node\Node;
8+
use drupol\phptree\Node\NodeInterface;
9+
10+
/**
11+
* Class SimpleArray
12+
*/
13+
class SimpleArray implements ImporterInterface
14+
{
15+
/**
16+
* {@inheritdoc}
17+
*/
18+
public function import($data): NodeInterface
19+
{
20+
return $this->arrayToTree($data);
21+
}
22+
23+
/**
24+
* Convert an array into a tree.
25+
*
26+
* @param array $data
27+
*
28+
* @return \drupol\phptree\Node\NodeInterface
29+
* The tree.
30+
*/
31+
protected function arrayToTree(array $data): NodeInterface
32+
{
33+
$data += [
34+
'children' => [],
35+
];
36+
37+
$node = $this->createNode($data['value']);
38+
39+
foreach ($data['children'] as $key => $child) {
40+
$node->add($this->arrayToTree($child));
41+
}
42+
43+
return $node;
44+
}
45+
46+
/**
47+
* Create a node.
48+
*
49+
* @param mixed $data
50+
* The arguments.
51+
*
52+
* @return \drupol\phptree\Node\NodeInterface
53+
* The node.
54+
*/
55+
protected function createNode($data): NodeInterface
56+
{
57+
return new Node();
58+
}
59+
}

0 commit comments

Comments
 (0)