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