1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* For the full copyright and license information, please view |
5
|
|
|
* the LICENSE file that was distributed with this source code. |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
declare(strict_types=1); |
9
|
|
|
|
10
|
|
|
namespace loophp\phptree\Importer; |
11
|
|
|
|
12
|
|
|
use loophp\phptree\Node\AttributeNode; |
13
|
|
|
use loophp\phptree\Node\AttributeNodeInterface; |
14
|
|
|
use loophp\phptree\Node\NodeInterface; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Class Text. |
18
|
|
|
*/ |
19
|
|
|
final class Text implements ImporterInterface |
20
|
|
|
{ |
21
|
2 |
|
public function import($data): NodeInterface |
22
|
|
|
{ |
23
|
2 |
|
return $this->parseNode(new AttributeNode(['label' => 'root']), $data); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Create a node. |
28
|
|
|
* |
29
|
|
|
* @param string $label |
30
|
|
|
* The node label |
31
|
|
|
* |
32
|
|
|
* @return AttributeNodeInterface |
33
|
|
|
* The node |
34
|
|
|
*/ |
35
|
2 |
|
private function createNode(string $label): AttributeNodeInterface |
36
|
|
|
{ |
37
|
2 |
|
return new AttributeNode([ |
38
|
2 |
|
'label' => $label, |
39
|
|
|
]); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Parse a string into an array. |
44
|
|
|
* |
45
|
|
|
* @param string $subject |
46
|
|
|
* The subject string |
47
|
|
|
* |
48
|
|
|
* @return array<string, mixed> |
49
|
|
|
* The array |
50
|
|
|
*/ |
51
|
2 |
|
private function parse(string $subject): array |
52
|
|
|
{ |
53
|
|
|
$result = [ |
54
|
2 |
|
'value' => substr($subject, 1, strpos($subject, '[', 1) - 1), |
55
|
|
|
'children' => [], |
56
|
|
|
]; |
57
|
|
|
|
58
|
2 |
|
if (false === $nextBracket = strpos($subject, '[', 1)) { |
59
|
2 |
|
return $result; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
// Todo: Improve the regex. |
63
|
2 |
|
preg_match_all('#[^\[\]]+|\[(?<nested>(?R)*)]#', substr($subject, $nextBracket, -1), $matches); |
64
|
|
|
|
65
|
2 |
|
$result['children'] = array_map( |
66
|
|
|
static function (string $match): string { |
67
|
2 |
|
return sprintf('[%s]', $match); |
68
|
2 |
|
}, |
69
|
2 |
|
array_filter((array) $matches['nested']) |
70
|
|
|
); |
71
|
|
|
|
72
|
2 |
|
return $result; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* @param string ...$nodes |
77
|
|
|
*/ |
78
|
2 |
|
private function parseNode(AttributeNodeInterface $parent, string ...$nodes): NodeInterface |
79
|
|
|
{ |
80
|
2 |
|
return array_reduce( |
81
|
2 |
|
$nodes, |
82
|
|
|
function (AttributeNodeInterface $carry, string $node): NodeInterface { |
83
|
2 |
|
$data = $this->parse($node); |
84
|
|
|
|
85
|
|
|
return $carry |
86
|
2 |
|
->add( |
87
|
2 |
|
$this->parseNode( |
88
|
2 |
|
$this->createNode($data['value']), |
89
|
2 |
|
...$data['children'] |
90
|
|
|
) |
91
|
|
|
); |
92
|
2 |
|
}, |
93
|
|
|
$parent |
94
|
|
|
); |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|