-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathGraphViz.php
More file actions
529 lines (460 loc) · 16.5 KB
/
GraphViz.php
File metadata and controls
529 lines (460 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
<?php
namespace Graphp\GraphViz;
use Graphp\Graph\Edge;
use Graphp\Graph\EdgeDirected;
use Graphp\Graph\Entity;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Graph;
use Graphp\Graph\Vertex;
class GraphViz
{
/**
* file output format to use
*
* @var string
* @see GraphViz::setFormat()
*/
private $format = 'png';
/**
* Either the name of full path to GraphViz layout.
*
* @var string
* @see GraphViz::setExecutable()
*/
private $executable = 'dot';
/**
* string to use as indentation for dot output
*
* @var string
* @see GraphViz::createScript()
*/
private $formatIndent = ' ';
private $attributeFlow = 'flow';
private $attributeCapacity = 'capacity';
private $attributeWeight = 'weight';
private $attributeGroup = 'group';
private $attributeBalance = 'balance';
private $ranks = array();
const DELAY_OPEN = 2.0;
const EOL = PHP_EOL;
public function __construct()
{
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$this->executable = 'dot.exe';
}
}
/**
* Change the executable to use.
*
* Usually, your graphviz executables should be located in your $PATH
* environment variable and invoking a mere `dot` is sufficient. If you
* have no access to your $PATH variable, use this method to set the path
* to your graphviz dot executable.
*
* This should contain '.exe' on windows.
* - /full/path/to/bin/dot
* - neato
* - dot.exe
* - c:\path\to\bin\dot.exe
*
* @param string $executable
* @return GraphViz $this (chainable)
*/
public function setExecutable($executable) {
$this->executable = $executable;
return $this;
}
/**
* return executable to use
*
* @return string
* @see GraphViz::setExecutable()
*/
public function getExecutable() {
return $this->executable;
}
/**
* set graph image output format
*
* @param string $format png, svg, ps2, etc. (see 'man dot' for details on parameter '-T')
* @return GraphViz $this (chainable)
*/
public function setFormat($format)
{
$this->format = $format;
return $this;
}
/**
* set rank for vertex
*
* @param int $rank
* @param string $vertex vertex have the same rank
* @param string $type "same", "min", "source", "max", "sink"
* @param string $group vertex in the subgraph
* @return GraphViz $this (chainable)
*/
public function setRank($rank, $vertex, $type = 'same', $group = null)
{
$id = \spl_object_hash($vertex);
if (isset($this->ranks[$group][$type][$rank])) {
$this->ranks[$group][$type][$rank][$id] = $id;
} else if (isset($this->ranks[$group][$type])) {
$this->ranks[$group][$type][$rank] = array($id => $id);
} else if (isset($this->ranks[$group])) {
$this->ranks[$group][$type] = array($rank => array($id => $id));
} else {
$this->ranks[$group] = array($type => array($rank => array($id => $id)));
}
return $this;
}
/**
* set rank for vertexes
*
* @param int $rank
* @param string $vertexes vertexs have the same rank
* @param string $type "same", "min", "source", "max", "sink"
* @param string $group vertex in the subgraph
* @return GraphViz $this (chainable)
*/
public function setRanks($rank, array $vertexes, $type = 'same', $group = null)
{
foreach ($vertexes as $vertex) {
$this->setRank($rank, $vertex, $type, $group);
}
return $this;
}
/**
* create and display image for this graph
*
* @param Graph $graph graph to display
* @return void
* @uses GraphViz::createImageFile()
*/
public function display(Graph $graph)
{
// echo "Generate picture ...";
$tmp = $this->createImageFile($graph);
static $next = 0;
if ($next > microtime(true)) {
// wait some time between calling xdg-open because earlier calls will be ignored otherwise
//echo '[delay flooding xdg-open]' . PHP_EOL;
sleep(self::DELAY_OPEN);
}
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
// open image in untitled, temporary background shell
exec('start "" ' . escapeshellarg($tmp) . ' >NUL');
} elseif (strtoupper(PHP_OS) === 'DARWIN') {
// open image in background (redirect stdout to /dev/null, sterr to stdout and run in background)
exec('open ' . escapeshellarg($tmp) . ' > /dev/null 2>&1 &');
} else {
// open image in background (redirect stdout to /dev/null, sterr to stdout and run in background)
exec('xdg-open ' . escapeshellarg($tmp) . ' > /dev/null 2>&1 &');
}
$next = microtime(true) + self::DELAY_OPEN;
// echo "... done\n";
}
/**
* create image file data contents for this graph
*
* @param Graph $graph graph to display
* @return string
* @uses GraphViz::createImageFile()
*/
public function createImageData(Graph $graph)
{
$file = $this->createImageFile($graph);
$data = file_get_contents($file);
unlink($file);
return $data;
}
/**
* create base64-encoded image src target data to be used for html images
*
* @param Graph $graph graph to display
* @return string
* @uses GraphViz::createImageData()
*/
public function createImageSrc(Graph $graph)
{
$format = $this->format;
if ($this->format === 'svg' || $this->format === 'svgz') {
$format = 'svg+xml;charset=' . $graph->getAttribute('graphviz.graph.charset', 'UTF-8');
}
return 'data:image/' . $format . ';base64,' . base64_encode($this->createImageData($graph));
}
/**
* create image html code for this graph
*
* @param Graph $graph graph to display
* @return string
* @uses GraphViz::createImageSrc()
*/
public function createImageHtml(Graph $graph)
{
if ($this->format === 'svg' || $this->format === 'svgz') {
return '<object type="image/svg+xml" data="' . $this->createImageSrc($graph) . '"></object>';
}
return '<img src="' . $this->createImageSrc($graph) . '" />';
}
/**
* create image file for this graph
*
* @param Graph $graph graph to display
* @return string filename
* @throws UnexpectedValueException on error
* @uses GraphViz::createScript()
*/
public function createImageFile(Graph $graph)
{
$script = $this->createScript($graph);
// var_dump($script);
$tmp = tempnam(sys_get_temp_dir(), 'graphviz');
if ($tmp === false) {
throw new UnexpectedValueException('Unable to get temporary file name for graphviz script');
}
$ret = file_put_contents($tmp, $script, LOCK_EX);
if ($ret === false) {
throw new UnexpectedValueException('Unable to write graphviz script to temporary file');
}
$ret = 0;
$executable = $this->getExecutable();
system(escapeshellarg($executable) . ' -T ' . escapeshellarg($this->format) . ' ' . escapeshellarg($tmp) . ' -o ' . escapeshellarg($tmp . '.' . $this->format), $ret);
if ($ret !== 0) {
throw new UnexpectedValueException('Unable to invoke "' . $executable .'" to create image file (code ' . $ret . ')');
}
unlink($tmp);
return $tmp . '.' . $this->format;
}
/**
* create graphviz script representing this graph
*
* @param Graph $graph graph to display
* @return string
* @uses Directed::hasDirected()
* @uses Graph::getVertices()
* @uses Graph::getEdges()
*/
public function createScript(Graph $graph)
{
$directed = false;
foreach ($graph->getEdges() as $edge) {
if ($edge instanceof EdgeDirected) {
$directed = true;
break;
}
}
/*
* The website [http://www.graphviz.org/content/dot-language] uses the term `ID` when displaying
* the abstract grammar for the DOT language.
* But the man pages for dot use the term `name` when describing the graph file language.
*/
$name = $graph->getAttribute('graphviz.name');
if ($name !== null) {
$name = $this->escape($name) . ' ';
}
$script = ($directed ? 'digraph ' : 'graph ') . $name . '{' . self::EOL;
// add global attributes
$globals = array(
'graph' => 'graphviz.graph.',
'node' => 'graphviz.node.',
'edge' => 'graphviz.edge.',
);
foreach ($globals as $key => $prefix) {
if ($layout = $this->getAttributesPrefixed($graph, $prefix)) {
$script .= $this->formatIndent . $key . ' ' . $this->escapeAttributes($layout) . self::EOL;
}
}
// build an array to map vertex hashes to vertex IDs for output
$tid = 0;
$vids = array();
$groupVertexs = array();
foreach ($graph->getVertices() as $vertex) {
//assert($vertex instanceof Vertex);
$groupVertexs[$vertex->getAttribute('group')][] = $vertex;
$id = $vertex->getAttribute('id');
if ($id === null) {
$id = ++$tid;
} else {
$id = $this->escape($id);
}
$vids[\spl_object_hash($vertex)] = $id;
}
$groupEdges = array();
// add all edges as directed edges
foreach ($graph->getEdges() as $edge) {
$groupEdges[$edge->getAttribute('group')][] = $edge;
}
$gid = 0;
$edgeop = $directed ? ' -> ' : ' -- ';
// put each group of vertices in a separate subgraph cluster
foreach ($groupVertexs as $group => $vertices) {
if ($group !== '') {
$indent = str_repeat($this->formatIndent, 2);
$script .= $this->formatIndent . 'subgraph cluster_' . $gid++ . ' {' .
self::EOL . $indent . 'label = ' . $this->escape($group) . self::EOL;
} else {
$indent = $this->formatIndent;
}
// explicitly add all isolated vertices (vertices with no edges) and vertices with special layout set
// other vertices wil be added automatically due to below edge definitions
foreach ($vertices as $vertex){
$vid = $vids[\spl_object_hash($vertex)];
$layout = $this->getLayoutVertex($vertex, $vid);
if ($layout || $vertex->getEdges()->isEmpty()) {
$script .= $indent . $vid;
if ($layout) {
$script .= ' ' . $this->escapeAttributes($layout);
}
$script .= self::EOL;
}
}
if (isset($groupEdges[$group])) {
foreach ($groupEdges[$group] as $edge) {
$both = $edge->getVertices()->getVector();
$startVertex = $both[0];
$targetVertex = $both[1];
$script .= $indent . $vids[\spl_object_hash($startVertex)] . $edgeop . $vids[\spl_object_hash($targetVertex)];
$layout = $this->getLayoutEdge($edge);
// this edge is not a loop and also points to the opposite direction => this is actually an undirected edge
if ($directed && $startVertex !== $targetVertex && $edge->isConnection($targetVertex, $startVertex)) {
$layout['dir'] = 'none';
}
if ($layout) {
$script .= ' ' . $this->escapeAttributes($layout);
}
$script .= self::EOL;
}
}
if (isset($this->ranks[$group])) {
foreach ($this->ranks[$group] as $type => $ranks) {
foreach ($ranks as $vers) {
$ids = [];
foreach ($vers as $id) {
$ids[] = $vids[$id];
}
$script .= $indent . '{rank=' . $type . ' ' . implode(' ', $ids) . '}' . self::EOL;
}
}
}
if ($group !== '') {
$script .= ' }' . self::EOL;
}
}
$script .= '}' . self::EOL;
return $script;
}
/**
* escape given string value and wrap in quotes if needed
*
* @param string $id
* @return string
* @link http://graphviz.org/content/dot-language
*/
private function escape($id)
{
// see @link: There is no semantic difference between abc_2 and "abc_2"
// numeric or simple string, no need to quote (only for simplicity)
if (preg_match('/^(?:\-?(?:\.\d+|\d+(?:\.\d+)?))$/i', $id)) {
return $id;
}
return '"' . str_replace(array('&', '<', '>', '"', "'", '\\', "\n"), array('&', '<', '>', '"', ''', '\\\\', '\\l'), $id) . '"';
}
/**
* get escaped attribute string for given array of (unescaped) attributes
*
* @param array $attrs
* @return string
* @uses GraphViz::escape()
*/
private function escapeAttributes($attrs)
{
$script = '[';
$first = true;
foreach ($attrs as $name => $value) {
if ($first) {
$first = false;
} else {
$script .= ' ';
}
if (\substr($name, -5) === '_html') {
// HTML-like labels need to be wrapped in angle brackets
$name = \substr($name, 0, -5);
$value = '<' . $value . '>';
} elseif (\substr($name, -7) === '_record') {
// record labels need to be quoted
$name = \substr($name, 0, -7);
$value = '"' . \str_replace('"', '\\"', $value) . '"';
} else {
// all normal attributes need to be escaped and/or quoted
$value = $this->escape($value);
}
$script .= $name . '=' . $value;
}
$script .= ']';
return $script;
}
private function getLayoutVertex(Vertex $vertex, $vid)
{
$layout = $this->getAttributesPrefixed($vertex, 'graphviz.');
$balance = $vertex->getAttribute($this->attributeBalance);
if ($balance !== NULL) {
if ($balance > 0) {
$balance = '+' . $balance;
}
if (!isset($layout['label'])) {
$layout['label'] = $vid;
}
$layout['label'] .= ' (' . $balance . ')';
}
return $layout;
}
protected function getLayoutEdge(Edge $edge)
{
$layout = $this->getAttributesPrefixed($edge, 'graphviz.');
// use flow/capacity/weight as edge label
$label = NULL;
$flow = $edge->getAttribute($this->attributeFlow);
$capacity = $edge->getAttribute($this->attributeCapacity);
// flow is set
if ($flow !== NULL) {
// NULL capacity = infinite capacity
$label = $flow . '/' . ($capacity === NULL ? '∞' : $capacity);
// capacity set, but not flow (assume zero flow)
} elseif ($capacity !== NULL) {
$label = '0/' . $capacity;
}
$weight = $edge->getAttribute($this->attributeWeight);
// weight is set
if ($weight !== NULL) {
if ($label === NULL) {
$label = $weight;
} else {
$label .= '/' . $weight;
}
}
if ($label !== NULL) {
if (isset($layout['label'])) {
$layout['label'] .= ' ' . $label;
} else {
$layout['label'] = $label;
}
}
return $layout;
}
/**
* @param Graph|Vertex|Edge $entity
* @param string $prefix
* @return array
*/
private function getAttributesPrefixed(Entity $entity, $prefix)
{
$len = \strlen($prefix);
$attributes = array();
foreach ($entity->getAttributes() as $name => $value) {
if (\strpos($name, $prefix) === 0) {
$attributes[substr($name, $len)] = $value;
}
}
return $attributes;
}
}