Passed
Push — master ( 04a345...2d2d6e )
by Pol
10:55
created

Graph::getGraph()   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
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace loophp\phptree\Exporter;
6
7
use Fhaculty\Graph\Graph as OriginalGraph;
8
use Fhaculty\Graph\Vertex;
9
use loophp\phptree\Node\AttributeNodeInterface;
10
use loophp\phptree\Node\NodeInterface;
11
12
final class Graph implements ExporterInterface
13
{
14
    public function export(NodeInterface $node): OriginalGraph
15
    {
16
        $graph = new OriginalGraph();
17
18
        foreach ($node->all() as $node_visited) {
19
            $vertexFrom = $this->createVertex($node_visited, $graph);
20
21
            foreach ($node_visited->children() as $child) {
22
                $vertexTo = $this->createVertex($child, $graph);
23
                $vertexFrom->createEdgeTo($vertexTo);
24
            }
25
        }
26
27 2
        return $graph;
28
    }
29 2
30
    /**
31 2
     * Create a vertex.
32 2
     *
33
     * @param NodeInterface $node
34 2
     *   The node
35 2
     *
36 2
     * @return Vertex
37
     *   A vertex
38
     */
39
    private function createVertex(NodeInterface $node, OriginalGraph $graph): Vertex
40 2
    {
41
        /** @var int $vertexId */
42
        $vertexId = $this->createVertexId($node);
43
44
        if (!$graph->hasVertex($vertexId)) {
45
            $vertex = $graph->createVertex($vertexId);
46
47
            $vertex->setAttribute(
48
                'graphviz.label',
49
                $node->label()
50
            );
51
52 2
            if ($node instanceof AttributeNodeInterface) {
53
                foreach ($node->getAttributes() as $key => $value) {
54
                    $vertex->setAttribute((string) $key, $value);
55 2
                }
56
            }
57 2
        }
58 2
59
        return $graph->getVertex($vertexId);
60 2
    }
61 2
62 2
    private function createVertexId(NodeInterface $node): string
63
    {
64
        return sha1(spl_object_hash($node));
65 2
    }
66
}
67