1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace loophp\phptree\Importer; |
6
|
|
|
|
7
|
|
|
use Exception; |
8
|
|
|
use loophp\phptree\Node\AttributeNode; |
9
|
|
|
use loophp\phptree\Node\AttributeNodeInterface; |
10
|
|
|
use loophp\phptree\Node\NodeInterface; |
11
|
|
|
use PhpParser\Node; |
12
|
|
|
|
13
|
|
|
use function is_array; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Class NikicPhpParser. |
17
|
|
|
*/ |
18
|
|
|
final class NikicPhpParser implements ImporterInterface |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @param Node[] $data |
22
|
|
|
* |
23
|
|
|
* @throws Exception |
24
|
|
|
* |
25
|
|
|
* @return NodeInterface |
26
|
|
|
*/ |
27
|
1 |
|
public function import($data): NodeInterface |
28
|
|
|
{ |
29
|
1 |
|
return $this->parseNode($this->createNode(['label' => 'root']), ...$data); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param array $attributes |
34
|
|
|
* |
35
|
|
|
* @return AttributeNodeInterface |
36
|
|
|
*/ |
37
|
1 |
|
private function createNode(array $attributes): AttributeNodeInterface |
38
|
|
|
{ |
39
|
1 |
|
return new AttributeNode($attributes); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param \PhpParser\Node $astNode |
44
|
|
|
* |
45
|
|
|
* @return array<int, Node> |
46
|
|
|
*/ |
47
|
1 |
|
private function getAllNodeChildren(Node $astNode): array |
48
|
|
|
{ |
49
|
|
|
/** @var array<int, array<int, Node>> $astNodes */ |
50
|
1 |
|
$astNodes = array_map( |
51
|
|
|
static function (string $subNodeName) use ($astNode): array { |
52
|
1 |
|
$subNodes = $astNode->{$subNodeName}; |
53
|
|
|
|
54
|
1 |
|
if (!is_array($subNodes)) { |
55
|
1 |
|
$subNodes = [$subNodes]; |
56
|
|
|
} |
57
|
|
|
|
58
|
1 |
|
return array_filter( |
59
|
1 |
|
$subNodes, |
60
|
1 |
|
'is_object' |
61
|
|
|
); |
62
|
1 |
|
}, |
63
|
1 |
|
$astNode->getSubNodeNames() |
64
|
|
|
); |
65
|
|
|
|
66
|
1 |
|
return [] === $astNodes ? |
67
|
|
|
[] : |
68
|
1 |
|
array_merge(...$astNodes); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* @param AttributeNodeInterface $parent |
73
|
|
|
* @param Node ...$astNodes |
74
|
|
|
* |
75
|
|
|
* @return NodeInterface |
76
|
|
|
*/ |
77
|
1 |
|
private function parseNode(AttributeNodeInterface $parent, Node ...$astNodes): NodeInterface |
78
|
|
|
{ |
79
|
1 |
|
return array_reduce( |
80
|
1 |
|
$astNodes, |
81
|
|
|
function (AttributeNodeInterface $carry, Node $astNode): NodeInterface { |
82
|
|
|
return $carry |
83
|
1 |
|
->add( |
84
|
1 |
|
$this->parseNode( |
85
|
1 |
|
$this->createNode([ |
86
|
1 |
|
'label' => $astNode->getType(), |
87
|
1 |
|
'astNode' => $astNode, |
88
|
|
|
]), |
89
|
1 |
|
...$this->getAllNodeChildren($astNode) |
90
|
|
|
) |
91
|
|
|
); |
92
|
1 |
|
}, |
93
|
|
|
$parent |
94
|
|
|
); |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|