Graph::createVertex()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

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