1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Cycle ORM Schema Builder. |
5
|
|
|
* |
6
|
|
|
* @license MIT |
7
|
|
|
* @author Anton Titov (Wolfy-J) |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
declare(strict_types=1); |
11
|
|
|
|
12
|
|
|
namespace Cycle\Schema\Generator; |
13
|
|
|
|
14
|
|
|
use Cycle\Schema\Exception\SyncException; |
15
|
|
|
use Cycle\Schema\GeneratorInterface; |
16
|
|
|
use Cycle\Schema\Registry; |
17
|
|
|
use Spiral\Database\Schema\Reflector; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Sync table schemas with database. |
21
|
|
|
*/ |
22
|
|
|
final class SyncTables implements GeneratorInterface |
23
|
|
|
{ |
24
|
|
|
// Readonly tables must be included form the sync with database |
25
|
|
|
public const READONLY_SCHEMA = 'readonlySchema'; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @param Registry $registry |
29
|
|
|
* |
30
|
|
|
* @return Registry |
31
|
|
|
* |
32
|
|
|
* @throws SyncException |
33
|
|
|
*/ |
34
|
|
|
public function run(Registry $registry): Registry |
35
|
|
|
{ |
36
|
|
|
foreach ($this->getRegistryDbList($registry) as $dbName) { |
37
|
|
|
$reflector = new Reflector(); |
38
|
|
|
|
39
|
|
|
foreach ($registry as $regEntity) { |
40
|
|
|
if ( |
41
|
|
|
!$registry->hasTable($regEntity) |
42
|
|
|
|| $registry->getDatabase($regEntity) !== $dbName |
43
|
|
|
|| $regEntity->getOptions()->has(SyncTables::READONLY_SCHEMA) |
44
|
|
|
) { |
45
|
|
|
continue; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$reflector->addTable($registry->getTableSchema($regEntity)); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
try { |
52
|
|
|
$reflector->run(); |
53
|
|
|
} catch (\Throwable $e) { |
54
|
|
|
throw new SyncException($e->getMessage(), $e->getCode(), $e); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
return $registry; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @param Registry $registry |
63
|
|
|
* |
64
|
|
|
* @return array |
65
|
|
|
*/ |
66
|
|
|
private function getRegistryDbList(Registry $registry): array |
67
|
|
|
{ |
68
|
|
|
$databases = []; |
69
|
|
|
foreach ($registry as $regEntity) { |
70
|
|
|
$dbName = $registry->getDatabase($regEntity); |
71
|
|
|
if (in_array($dbName, $databases, true)) { |
72
|
|
|
continue; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
$databases[] = $dbName; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return $databases; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|