Passed
Pull Request — master (#8)
by
unknown
01:45
created

SyncTables::getRegistryDbList()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 13
rs 10
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
                $reflector->addTable($registry->getTableSchema($regEntity));
48
            }
49
50
            try {
51
                $reflector->run();
52
            } catch (\Throwable $e) {
53
                throw new SyncException($e->getMessage(), $e->getCode(), $e);
54
            }
55
        }
56
57
        return $registry;
58
    }
59
60
    /**
61
     * @param Registry $registry
62
     *
63
     * @return array
64
     */
65
    private function getRegistryDbList(Registry $registry): array
66
    {
67
        $databases = [];
68
        foreach ($registry as $regEntity) {
69
            $dbName = $registry->getDatabase($regEntity);
70
            if (in_array($dbName, $databases, true)) {
71
                continue;
72
            }
73
74
            $databases[] = $dbName;
75
        }
76
77
        return $databases;
78
    }
79
}
80