Completed
Push — master ( 90b292...6ee589 )
by Dawid
05:20
created

MigrationManager   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 24
dl 0
loc 64
ccs 28
cts 28
cp 1
rs 10
c 0
b 0
f 0
wmc 14

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A findNewestVersion() 0 11 3
B migrate() 0 24 8
A getCurrentVersion() 0 3 1
A register() 0 3 1
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
class MigrationManager
9
{
10
    /**
11
     * @var VersionSynchronizer
12
     */
13
    private $synchronizer;
14
15
    /**
16
     * @var Migration[]
17
     */
18
    private $migrations = [];
19
20 5
    public function __construct(VersionSynchronizer $synchronizer)
21
    {
22 5
        $this->synchronizer = $synchronizer;
23 5
    }
24
25 3
    public function register(Migration $migration): void
26
    {
27 3
        $this->migrations[] = $migration;
28 3
    }
29
30 1
    public function getCurrentVersion(): Version
31
    {
32 1
        return $this->synchronizer->getVersion();
33
    }
34
35 2
    public function migrate(Version $targetVersion = null): Version
36
    {
37 2
        $lastVersion = $this->synchronizer->getVersion();
38 2
        if ($targetVersion === null) {
39 1
            $targetVersion = $this->findNewestVersion();
40
        }
41
42 2
        if ($targetVersion->greaterThan($lastVersion)) {
43 1
            foreach ($this->migrations as $migration) {
44 1
                if ($migration->getVersion()->lowerOrEquals($targetVersion)) {
45 1
                    $migration->up();
46
                }
47
            }
48 1
        } else if ($targetVersion->lowerThan($lastVersion)) {
49 1
            foreach ($this->migrations as $migration) {
50 1
                if ($migration->getVersion()->greaterThan($targetVersion)) {
51 1
                    $migration->down();
52
                }
53
            }
54
        }
55
56 2
        $this->synchronizer->setVersion($targetVersion);
57
58 2
        return $targetVersion;
59
    }
60
61 1
    private function findNewestVersion(): Version
62
    {
63 1
        $version = Version::fromString('0.0.0');
64
65 1
        foreach ($this->migrations as $migration) {
66 1
            if ($migration->getVersion()->greaterThan($version)) {
67 1
                $version = clone $migration->getVersion();
68
            }
69
        }
70
71 1
        return $version;
72
    }
73
}
74