1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Cycle\Schema\Generator; |
6
|
|
|
|
7
|
|
|
use Cycle\Database\Schema\AbstractTable; |
8
|
|
|
use Cycle\Database\Schema\Reflector; |
9
|
|
|
use Cycle\Schema\Definition\Entity; |
10
|
|
|
use Cycle\Schema\GeneratorInterface; |
11
|
|
|
use Cycle\Schema\Registry; |
12
|
|
|
use Cycle\Schema\Table\Column; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Generate table columns based on entity definition. |
16
|
|
|
*/ |
17
|
|
|
final class RenderTables implements GeneratorInterface |
18
|
|
|
{ |
19
|
|
|
private Reflector $reflector; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* TableGenerator constructor. |
23
|
|
|
*/ |
24
|
416 |
|
public function __construct() |
25
|
|
|
{ |
26
|
416 |
|
$this->reflector = new Reflector(); |
27
|
416 |
|
} |
28
|
|
|
|
29
|
408 |
|
public function run(Registry $registry): Registry |
30
|
|
|
{ |
31
|
408 |
|
foreach ($registry as $entity) { |
32
|
408 |
|
$this->compute($registry, $entity); |
33
|
|
|
} |
34
|
|
|
|
35
|
408 |
|
return $registry; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* List of all involved tables sorted in order of their dependency. |
40
|
|
|
* |
41
|
|
|
* @return AbstractTable[] |
42
|
|
|
*/ |
43
|
|
|
public function getTables(): array |
44
|
|
|
{ |
45
|
|
|
return $this->reflector->sortedTables(); |
46
|
|
|
} |
47
|
|
|
|
48
|
216 |
|
public function getReflector(): Reflector |
49
|
|
|
{ |
50
|
216 |
|
return $this->reflector; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Generate table schema based on given entity definition. |
55
|
|
|
*/ |
56
|
408 |
|
private function compute(Registry $registry, Entity $entity): void |
57
|
|
|
{ |
58
|
408 |
|
if (!$registry->hasTable($entity)) { |
59
|
|
|
// do not render entities without associated table |
60
|
16 |
|
return; |
61
|
|
|
} |
62
|
|
|
|
63
|
408 |
|
$table = $registry->getTableSchema($entity); |
64
|
|
|
|
65
|
408 |
|
$primaryKeys = []; |
66
|
408 |
|
foreach ($entity->getFields() as $field) { |
67
|
408 |
|
$column = Column::parse($field); |
68
|
|
|
|
69
|
408 |
|
if ($column->isPrimary()) { |
70
|
408 |
|
$primaryKeys[] = $field->getColumn(); |
71
|
|
|
} |
72
|
|
|
|
73
|
408 |
|
$column->render($table->column($field->getColumn())); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
// todo fix discriminator column name |
77
|
|
|
// if ($registry->getChildren($entity) !== []) { |
78
|
|
|
// if (!$table->hasColumn(Mapper::ENTITY_TYPE)) { |
79
|
|
|
// $table->string(Mapper::ENTITY_TYPE, 32); |
80
|
|
|
// } |
81
|
|
|
// } |
82
|
|
|
|
83
|
408 |
|
if (count($primaryKeys)) { |
84
|
408 |
|
$table->setPrimaryKeys($primaryKeys); |
85
|
|
|
} |
86
|
|
|
|
87
|
408 |
|
$this->reflector->addTable($table); |
88
|
408 |
|
} |
89
|
|
|
} |
90
|
|
|
|