Passed
Pull Request — 1.x (#12)
by
unknown
29:27 queued 14:24
created

MermaidRenderer::render()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 40
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 40
rs 8.6186
cc 7
nc 10
nop 1
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