1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Cycle\Schema\Renderer\MermaidRenderer; |
6
|
|
|
|
7
|
|
|
use Cycle\ORM\Relation; |
8
|
|
|
use Cycle\ORM\SchemaInterface; |
9
|
|
|
use Cycle\Schema\Renderer\MermaidRenderer\Entity\EntityArrow; |
10
|
|
|
use Cycle\Schema\Renderer\MermaidRenderer\Entity\EntityTable; |
11
|
|
|
use Cycle\Schema\Renderer\MermaidRenderer\Exception\RelationNotFoundException; |
12
|
|
|
use Cycle\Schema\Renderer\SchemaRenderer; |
13
|
|
|
|
14
|
|
|
final class MermaidRenderer implements SchemaRenderer |
15
|
|
|
{ |
16
|
|
|
public const DIAGRAM = <<<DIAGRAM |
17
|
|
|
|
18
|
|
|
erDiagram |
19
|
|
|
%s |
20
|
|
|
|
21
|
|
|
DIAGRAM; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @throws RelationNotFoundException |
25
|
|
|
*/ |
26
|
|
|
public function render(array $schema): string |
27
|
|
|
{ |
28
|
|
|
$relationMapper = new RelationMapper(); |
29
|
|
|
|
30
|
|
|
$blocks = []; |
31
|
|
|
|
32
|
|
|
foreach ($schema as $key => $value) { |
33
|
|
|
if (!isset($value[SchemaInterface::COLUMNS], $value[SchemaInterface::RELATIONS])) { |
34
|
|
|
continue; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
$table = new EntityTable($key); |
38
|
|
|
$arrow = new EntityArrow(); |
39
|
|
|
|
40
|
|
|
foreach ($value[SchemaInterface::COLUMNS] as $column) { |
41
|
|
|
$table->addRow($value[SchemaInterface::TYPECAST][$column] ?? 'string', $column); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
foreach ($value[SchemaInterface::RELATIONS] as $relation) { |
45
|
|
|
if (!isset($relation[Relation::TARGET], $relation[Relation::SCHEMA])) { |
46
|
|
|
continue; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
$target = $relation[Relation::TARGET]; |
50
|
|
|
$throughEntity = $relation[Relation::SCHEMA][Relation::THROUGH_ENTITY] ?? null; |
51
|
|
|
$isNullable = $relation[Relation::SCHEMA][Relation::NULLABLE] ?? false; |
52
|
|
|
$relation = $relationMapper->mapWithNode($relation[Relation::TYPE], $isNullable); |
53
|
|
|
|
54
|
|
|
if ($throughEntity) { |
55
|
|
|
$arrow->addArrow($key, $throughEntity, $relation[0], $relation[1]); |
56
|
|
|
$arrow->addArrow($target, $throughEntity, $relation[0], $relation[1]); |
57
|
|
|
} else { |
58
|
|
|
$arrow->addArrow($key, $target, $relation[0], $relation[1]); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
$blocks[] = $table->toString(); |
63
|
|
|
$blocks[] = $arrow->toString(); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return sprintf(self::DIAGRAM, implode("\n", $blocks)); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|