|
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
|
|
|
* Generate table schema based on given entity definition. |
|
36
|
|
|
* |
|
37
|
|
|
* @param Registry $registry |
|
38
|
|
|
* @param Entity $entity |
|
39
|
|
|
*/ |
|
40
|
|
|
public function compute(Registry $registry, Entity $entity) |
|
41
|
|
|
{ |
|
42
|
|
|
if (!$registry->hasTable($entity)) { |
|
43
|
|
|
// do not render entities without associated table |
|
44
|
|
|
return; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
$table = $registry->getTableSchema($entity); |
|
48
|
|
|
|
|
49
|
|
|
$primaryKeys = []; |
|
50
|
|
|
foreach ($entity->getFields() as $field) { |
|
51
|
|
|
$column = ColumnSchema::parse($field); |
|
52
|
|
|
|
|
53
|
|
|
if ($column->isPrimary()) { |
|
54
|
|
|
$primaryKeys[] = $field->getColumn(); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
$column->render($table->column($field->getColumn())); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
if (count($primaryKeys)) { |
|
61
|
|
|
$table->setPrimaryKeys($primaryKeys); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
$this->reflector->addTable($table); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
/** |
|
68
|
|
|
* @return Reflector |
|
69
|
|
|
*/ |
|
70
|
|
|
public function getReflector(): Reflector |
|
71
|
|
|
{ |
|
72
|
|
|
return $this->reflector; |
|
73
|
|
|
} |
|
74
|
|
|
} |