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