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
|
|
|
/** |
13
|
|
|
* Class Graph. |
14
|
|
|
*/ |
15
|
|
|
final class Graph implements ExporterInterface |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* The graph. |
19
|
|
|
* |
20
|
|
|
* @var \Fhaculty\Graph\Graph |
21
|
|
|
*/ |
22
|
|
|
private $graph; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* {@inheritdoc} |
26
|
|
|
*/ |
27
|
2 |
|
public function export(NodeInterface $node): OriginalGraph |
28
|
|
|
{ |
29
|
2 |
|
$this->graph = new OriginalGraph(); |
30
|
|
|
|
31
|
2 |
|
foreach ($node->all() as $node_visited) { |
32
|
2 |
|
$vertexFrom = $this->createVertex($node_visited); |
33
|
|
|
|
34
|
2 |
|
foreach ($node_visited->children() as $child) { |
35
|
2 |
|
$vertexTo = $this->createVertex($child); |
36
|
2 |
|
$vertexFrom->createEdgeTo($vertexTo); |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
|
40
|
2 |
|
return $this->getGraph(); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Create a vertex. |
45
|
|
|
* |
46
|
|
|
* @param NodeInterface $node |
47
|
|
|
* The node |
48
|
|
|
* |
49
|
|
|
* @return Vertex |
50
|
|
|
* A vertex |
51
|
|
|
*/ |
52
|
2 |
|
private function createVertex(NodeInterface $node): Vertex |
53
|
|
|
{ |
54
|
|
|
/** @var int $vertexId */ |
55
|
2 |
|
$vertexId = $this->createVertexId($node); |
56
|
|
|
|
57
|
2 |
|
if (!$this->getGraph()->hasVertex($vertexId)) { |
58
|
2 |
|
$vertex = $this->getGraph()->createVertex($vertexId); |
59
|
|
|
|
60
|
2 |
|
$vertex->setAttribute( |
61
|
2 |
|
'graphviz.label', |
62
|
2 |
|
$node->label() |
63
|
|
|
); |
64
|
|
|
|
65
|
2 |
|
if ($node instanceof AttributeNodeInterface) { |
66
|
1 |
|
foreach ($node->getAttributes() as $key => $value) { |
67
|
1 |
|
$vertex->setAttribute((string) $key, $value); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
72
|
2 |
|
return $this->getGraph()->getVertex($vertexId); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* Create a vertex ID. |
77
|
|
|
* |
78
|
|
|
* @param NodeInterface $node |
79
|
|
|
* The node |
80
|
|
|
* |
81
|
|
|
* @return string |
82
|
|
|
* A vertex ID |
83
|
|
|
*/ |
84
|
2 |
|
private function createVertexId(NodeInterface $node): string |
85
|
|
|
{ |
86
|
2 |
|
return sha1(spl_object_hash($node)); |
87
|
|
|
} |
88
|
|
|
|
89
|
2 |
|
private function getGraph(): OriginalGraph |
90
|
|
|
{ |
91
|
2 |
|
return $this->graph; |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|