Passed
Push — master ( 97996b...04a345 )
by Pol
02:40
created

NikicPhpParser::createNode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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 1
    public function import($data): NodeInterface
26
    {
27 1
        return $this->parseNode($this->createNode(['label' => 'root']), ...$data);
28
    }
29
30 1
    private function createNode(array $attributes): AttributeNodeInterface
31
    {
32 1
        return new AttributeNode($attributes);
33
    }
34
35
    /**
36
     * @return array<int, Node>
37
     */
38 1
    private function getAllNodeChildren(Node $astNode): array
39
    {
40
        /** @var array<int, array<int, Node>> $astNodes */
41 1
        $astNodes = array_map(
42
            static function (string $subNodeName) use ($astNode): array {
43 1
                $subNodes = $astNode->{$subNodeName};
44
45 1
                if (!is_array($subNodes)) {
46 1
                    $subNodes = [$subNodes];
47
                }
48
49 1
                return array_filter(
50 1
                    $subNodes,
51 1
                    'is_object'
52
                );
53 1
            },
54 1
            $astNode->getSubNodeNames()
55
        );
56
57 1
        return [] === $astNodes ?
58 1
            [] :
59 1
            array_merge(...$astNodes);
60
    }
61
62
    /**
63
     * @param Node ...$astNodes
64
     */
65 1
    private function parseNode(AttributeNodeInterface $parent, Node ...$astNodes): NodeInterface
66
    {
67 1
        return array_reduce(
68 1
            $astNodes,
69
            function (AttributeNodeInterface $carry, Node $astNode): NodeInterface {
70
                return $carry
71 1
                    ->add(
72 1
                        $this->parseNode(
73 1
                            $this->createNode([
74 1
                                'label' => $astNode->getType(),
75 1
                                'astNode' => $astNode,
76
                            ]),
77 1
                            ...$this->getAllNodeChildren($astNode)
78
                        )
79
                    );
80 1
            },
81
            $parent
82
        );
83
    }
84
}
85