MigrationManager::migrate()   B
last analyzed

Complexity

Conditions 8
Paths 6

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 8

Importance

Changes 0
Metric Value
cc 8
eloc 13
nc 6
nop 1
dl 0
loc 24
ccs 14
cts 14
cp 1
crap 8
rs 8.4444
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Igni\Storage;
4
5
use Igni\Storage\Migration\Version;
6
use Igni\Storage\Migration\VersionSynchronizer;
7
8
/**
9
 * Lightweight migration system usable with multiple databases.
10
 * Using migration manager one must implement VersionSynchronizer
11
 * which is responsible for providing current system version as well
12
 * as storing version used by migration.
13
 *
14
 * @see \Igni\Storage\Migration\VersionSynchronizer
15
 * @package Igni\Storage
16
 */
17
class MigrationManager
18
{
19
    /**
20
     * @var VersionSynchronizer
21
     */
22
    private $synchronizer;
23
24
    /**
25
     * @var Migration[]
26
     */
27
    private $migrations = [];
28
29 5
    public function __construct(VersionSynchronizer $synchronizer)
30
    {
31 5
        $this->synchronizer = $synchronizer;
32 5
    }
33
34 3
    public function register(Migration $migration): void
35
    {
36 3
        $this->migrations[] = $migration;
37 3
    }
38
39 1
    public function getCurrentVersion(): Version
40
    {
41 1
        return $this->synchronizer->getVersion();
42
    }
43
44 2
    public function migrate(Version $targetVersion = null): Version
45
    {
46 2
        $lastVersion = $this->synchronizer->getVersion();
47 2
        if ($targetVersion === null) {
48 1
            $targetVersion = $this->findNewestVersion();
49
        }
50
51 2
        if ($targetVersion->greaterThan($lastVersion)) {
52 1
            foreach ($this->migrations as $migration) {
53 1
                if ($migration->getVersion()->lowerOrEquals($targetVersion)) {
54 1
                    $migration->up();
55
                }
56
            }
57 1
        } else if ($targetVersion->lowerThan($lastVersion)) {
58 1
            foreach ($this->migrations as $migration) {
59 1
                if ($migration->getVersion()->greaterThan($targetVersion)) {
60 1
                    $migration->down();
61
                }
62
            }
63
        }
64
65 2
        $this->synchronizer->setVersion($targetVersion);
66
67 2
        return $targetVersion;
68
    }
69
70 1
    private function findNewestVersion(): Version
71
    {
72 1
        $version = Version::fromString('0.0.0');
73
74 1
        foreach ($this->migrations as $migration) {
75 1
            if ($migration->getVersion()->greaterThan($version)) {
76 1
                $version = clone $migration->getVersion();
77
            }
78
        }
79
80 1
        return $version;
81
    }
82
}
83