Passed
Pull Request — master (#8)
by
unknown
02:17 queued 25s
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 ($registry->getDatabase($regEntity) !== $dbName) {
41
                    continue;
42
                }
43
                $reflector->addTable($registry->getTableSchema($regEntity));
44
            }
45
46
            try {
47
                $reflector->run();
48
            } catch (\Throwable $e) {
49
                throw new SyncException($e->getMessage(), $e->getCode(), $e);
50
            }
51
        }
52
53
        return $registry;
54
    }
55
56
    /**
57
     * @param Registry $registry
58
     *
59
     * @return array
60
     */
61
    private function getRegistryDbList(Registry $registry): array
62
    {
63
        $databases = [];
64
        foreach ($registry as $regEntity) {
65
            $dbName = $registry->getDatabase($regEntity);
66
            if (in_array($dbName, $databases, true)) {
67
                continue;
68
            }
69
70
            $databases[] = $dbName;
71
        }
72
73
        return $databases;
74
    }
75
}
76