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\SchemaRenderer; |
12
|
|
|
|
13
|
|
|
final class MermaidRenderer implements SchemaRenderer |
14
|
|
|
{ |
15
|
|
|
public const DIAGRAM = <<<DIAGRAM |
16
|
|
|
|
17
|
|
|
erDiagram |
18
|
|
|
%s |
19
|
|
|
DIAGRAM; |
20
|
|
|
|
21
|
|
|
public function render(array $schema): string |
22
|
|
|
{ |
23
|
|
|
$relationMapper = new RelationMapper(); |
24
|
|
|
|
25
|
|
|
$blocks = []; |
26
|
|
|
|
27
|
|
|
foreach ($schema as $key => $value) { |
28
|
|
|
if (!isset($value[SchemaInterface::COLUMNS], $value[SchemaInterface::RELATIONS])) { |
29
|
|
|
continue; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
$table = new EntityTable($key); |
33
|
|
|
$arrow = new EntityArrow($key); |
34
|
|
|
|
35
|
|
|
foreach ($value[SchemaInterface::COLUMNS] as $column) { |
36
|
|
|
$table->addRow($value[SchemaInterface::TYPECAST][$column] ?? 'string', $column); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
foreach ($value[SchemaInterface::RELATIONS] as $relation) { |
40
|
|
|
if (!isset($relation[Relation::TARGET], $relation[Relation::SCHEMA])) { |
41
|
|
|
continue; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
$target = $relation[Relation::TARGET]; |
45
|
|
|
$throughEntity = $relation[Relation::SCHEMA][Relation::THROUGH_ENTITY] ?? null; |
46
|
|
|
$isNullable = $relation[Relation::SCHEMA][Relation::NULLABLE] ?? false; |
47
|
|
|
$relation = $relationMapper->map($relation[Relation::TYPE]); |
48
|
|
|
|
49
|
|
|
if ($throughEntity) { |
50
|
|
|
$arrow->addArrow($throughEntity, $relation, $isNullable); |
51
|
|
|
} else { |
52
|
|
|
$arrow->addArrow($target, $relation, $isNullable); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
$blocks[] = $table->toString(); |
57
|
|
|
$blocks[] = $arrow->toString(); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return sprintf(self::DIAGRAM, implode("\n", $blocks)); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|