SyncTables::run()   B
last analyzed

Complexity

Conditions 7
Paths 7

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 7.7656

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 7
eloc 14
nc 7
nop 1
dl 0
loc 25
ccs 9
cts 12
cp 0.75
crap 7.7656
rs 8.8333
c 3
b 1
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cycle\Schema\Generator;
6
7
use Cycle\Schema\Exception\SyncException;
8
use Cycle\Schema\GeneratorInterface;
9
use Cycle\Schema\Registry;
10
use Cycle\Database\Schema\Reflector;
11
12
/**
13
 * Sync table schemas with database.
14
 */
15
final class SyncTables implements GeneratorInterface
16
{
17
    // Readonly tables must be included form the sync with database
18
    public const READONLY_SCHEMA = 'readonlySchema';
19
20
    /**
21
     *
22
     * @throws SyncException
23
     *
24
     */
25
    public function run(Registry $registry): Registry
26
    {
27 16
        foreach ($this->getRegistryDbList($registry) as $dbName) {
28
            $reflector = new Reflector();
29 16
30 16
            foreach ($registry as $regEntity) {
31
                if (
32 16
                    !$registry->hasTable($regEntity)
33
                    || $registry->getDatabase($regEntity) !== $dbName
34 16
                    || $regEntity->getOptions()->has(self::READONLY_SCHEMA)
35 16
                ) {
36 16
                    continue;
37
                }
38
39
                $reflector->addTable($registry->getTableSchema($regEntity));
40
            }
41 16
42
            try {
43
                $reflector->run();
44
            } catch (\Throwable $e) {
45 16
                throw new SyncException($e->getMessage(), (int) $e->getCode(), $e);
46
            }
47
        }
48
49
        return $registry;
50
    }
51 16
52
    private function getRegistryDbList(Registry $registry): array
53
    {
54
        $databases = [];
55
        foreach ($registry as $regEntity) {
56
            if (!$registry->hasTable($regEntity)) {
57
                continue;
58
            }
59 16
            $dbName = $registry->getDatabase($regEntity);
60
            if (in_array($dbName, $databases, true)) {
61 16
                continue;
62 16
            }
63 16
64
            $databases[] = $dbName;
65
        }
66 16
67 16
        return $databases;
68 16
    }
69
}
70