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\Reflector; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Generate table columns based on entity definition. |
20
|
|
|
*/ |
21
|
|
|
final class RenderTable implements GeneratorInterface |
22
|
|
|
{ |
23
|
|
|
/** @var Reflector */ |
24
|
|
|
private $reflector; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* TableGenerator constructor. |
28
|
|
|
*/ |
29
|
|
|
public function __construct() |
30
|
|
|
{ |
31
|
|
|
$this->reflector = new Reflector(); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param Registry $registry |
36
|
|
|
* @return Registry |
37
|
|
|
*/ |
38
|
|
|
public function run(Registry $registry): Registry |
39
|
|
|
{ |
40
|
|
|
foreach ($registry as $entity) { |
41
|
|
|
$this->compute($registry, $entity); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
return $registry; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Generate table schema based on given entity definition. |
49
|
|
|
* |
50
|
|
|
* @param Registry $registry |
51
|
|
|
* @param Entity $entity |
52
|
|
|
*/ |
53
|
|
|
protected function compute(Registry $registry, Entity $entity) |
54
|
|
|
{ |
55
|
|
|
if (!$registry->hasTable($entity)) { |
56
|
|
|
// do not render entities without associated table |
57
|
|
|
return; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$table = $registry->getTableSchema($entity); |
61
|
|
|
|
62
|
|
|
$primaryKeys = []; |
63
|
|
|
foreach ($entity->getFields() as $field) { |
64
|
|
|
$column = ColumnSchema::parse($field); |
65
|
|
|
|
66
|
|
|
if ($column->isPrimary()) { |
67
|
|
|
$primaryKeys[] = $field->getColumn(); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
$column->render($table->column($field->getColumn())); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
if (count($primaryKeys)) { |
74
|
|
|
$table->setPrimaryKeys($primaryKeys); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
$this->reflector->addTable($table); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* @return Reflector |
82
|
|
|
*/ |
83
|
|
|
public function getReflector(): Reflector |
84
|
|
|
{ |
85
|
|
|
return $this->reflector; |
86
|
|
|
} |
87
|
|
|
} |