Skip to content

Commit e136a4d

Browse files
committed
Update the Text importer and increase code coverage.
1 parent 8a93bcd commit e136a4d

File tree

2 files changed

+23
-20
lines changed

2 files changed

+23
-20
lines changed

spec/drupol/phptree/Importer/TextSpec.php

+9
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,13 @@ public function it_can_import()
4343
->isRoot()
4444
->shouldReturn(TRUE);
4545
}
46+
47+
public function it_can_throw_an_error_when_cannot_import()
48+
{
49+
$string = 'invalid string';
50+
51+
$this
52+
->shouldThrow(\InvalidArgumentException::class)
53+
->during('import', [$string]);
54+
}
4655
}

src/Importer/Text.php

+14-20
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,11 @@
66

77
use drupol\phptree\Node\NodeInterface;
88
use drupol\phptree\Node\ValueNode;
9-
use drupol\phptree\Node\ValueNodeInterface;
109

1110
/**
1211
* Class Text
1312
*/
14-
class Text implements ImporterInterface
13+
class Text extends SimpleArray
1514
{
1615
/**
1716
* {@inheritdoc}
@@ -20,30 +19,25 @@ public function import($data): NodeInterface
2019
{
2120
$parsed = $this->parse($data);
2221

22+
if ([] === $parsed) {
23+
throw new \InvalidArgumentException('Unable to import the given data.');
24+
}
25+
2326
return $this->arrayToTree($parsed[0]);
2427
}
2528

2629
/**
27-
* Convert an array into a tree.
30+
* Create a node.
2831
*
29-
* @param array $data
32+
* @param mixed $arguments
33+
* The arguments.
3034
*
31-
* @return \drupol\phptree\Node\ValueNodeInterface
32-
* The tree.
35+
* @return \drupol\phptree\Node\Node
36+
* The node.
3337
*/
34-
private function arrayToTree(array $data): ValueNodeInterface
38+
protected function createNode($arguments): NodeInterface
3539
{
36-
$data += [
37-
'children' => [],
38-
];
39-
40-
$node = new ValueNode($data['value']);
41-
42-
foreach ($data['children'] as $key => $child) {
43-
$node->add($this->arrayToTree($child));
44-
}
45-
46-
return $node;
40+
return new ValueNode($arguments);
4741
}
4842

4943
/**
@@ -57,7 +51,7 @@ private function arrayToTree(array $data): ValueNodeInterface
5751
*/
5852
private function parse(string $subject)
5953
{
60-
$result = false;
54+
$result = [];
6155

6256
\preg_match_all('~[^\[\]]+|\[(?<nested>(?R)*)\]~', $subject, $matches);
6357

@@ -71,7 +65,7 @@ private function parse(string $subject)
7165
$item['value'] = $match;
7266
}
7367

74-
if (false !== $children = $this->parse($match)) {
68+
if ([] !== $children = $this->parse($match)) {
7569
$item['children'] = $children;
7670
}
7771

0 commit comments

Comments
 (0)