Completed
Push — master ( 3c84e0...8482f5 )
by max
02:01
created

Migration::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 11
rs 9.4285
cc 1
eloc 9
nc 1
nop 4
1
<?php
2
3
namespace T4web\Migrations\Service;
4
5
use Zend\Db\Adapter\Exception\InvalidQueryException;
6
use Zend\Db\Sql\Ddl;
7
use Zend\ServiceManager\ServiceLocatorInterface;
8
use Zend\Console\Adapter\Posix as Console;
9
use T4web\Migrations\Migration\AbstractMigration;
10
use T4web\Migrations\Config;
11
use T4web\Migrations\MigrationVersion\Table;
12
13
/**
14
 * Main migration logic
15
 */
16
class Migration
17
{
18
    /**
19
     * @var Table
20
     */
21
    protected $versionTable;
22
23
    /**
24
     * @var Console
25
     */
26
    protected $console;
27
28
    /**
29
     * @var ServiceLocatorInterface
30
     */
31
    protected $serviceLocator;
32
33
    /**
34
     * @param Table                    $versionTable
35
     * @param VersionResolver          $versionResolver
36
     * @param Console                  $console
37
     * @param ServiceLocatorInterface  $serviceLocator
38
     * @throws \Exception
39
     */
40
    public function __construct(
41
        VersionResolver $versionResolver,
42
        Table $versionTable,
43
        Console $console,
44
        ServiceLocatorInterface $serviceLocator = null
45
    ) {
46
        $this->versionResolver = $versionResolver;
0 ignored issues
show
Bug introduced by
The property versionResolver does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
47
        $this->versionTable = $versionTable;
48
        $this->console = $console;
49
        $this->serviceLocator = $serviceLocator;
50
    }
51
52
    /**
53
     * @param int $version target migration version, if not set all not applied available migrations will be applied
54
     * @param bool $force force apply migration
55
     * @param bool $down rollback migration
56
     * @param bool $fake
57
     * @throws \Exception
58
     */
59
    public function migrate($version = null, $force = false, $down = false, $fake = false)
60
    {
61
        $migrations = $this->versionResolver->getAll($force);
62
63
        if (!is_null($version) && !$this->hasMigrationVersions($migrations, $version)) {
64
            throw new \Exception(sprintf('Migration version %s is not found!', $version));
65
        }
66
67
        $currentMigrationVersion = $this->versionTable->getCurrentVersion();
68
        if (!is_null($version) && $version == $currentMigrationVersion && !$force) {
69
            throw new \Exception(sprintf('Migration version %s is current version!', $version));
70
        }
71
72
        if ($version && $force) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $version of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
73
            foreach ($migrations as $migration) {
74
                if ($migration['version'] == $version) {
75
                    // if existing migration is forced to apply - delete its information from migrated
76
                    // to avoid duplicate key error
77
                    if (!$down) {
78
                        $this->versionTable->delete($migration['version']);
79
                    }
80
                    $this->applyMigration($migration, $down, $fake);
81
                    break;
82
                }
83
            }
84
85
            return;
86
        }
87
88
        foreach ($this->versionResolver->getAll() as $migration) {
89
            $this->applyMigration($migration, false, $fake);
90
        }
91
    }
92
93
    /**
94
     * @param \ArrayIterator $migrations
95
     * @return \ArrayIterator
96
     */
97
    public function sortMigrationsByVersionDesc(\ArrayIterator $migrations)
98
    {
99
        $sortedMigrations = clone $migrations;
100
101
        $sortedMigrations->uasort(
102 View Code Duplication
            function ($a, $b) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
103
                if ($a['version'] == $b['version']) {
104
                    return 0;
105
                }
106
107
                return ($a['version'] > $b['version']) ? -1 : 1;
108
            }
109
        );
110
111
        return $sortedMigrations;
112
    }
113
114
    /**
115
     * Check migrations classes existence
116
     *
117
     * @param \ArrayIterator $migrations
118
     * @param int            $version
119
     * @return bool
120
     */
121
    public function hasMigrationVersions(\ArrayIterator $migrations, $version)
122
    {
123
        foreach ($migrations as $migration) {
124
            if ($migration['version'] == $version) {
125
                return true;
126
            }
127
        }
128
129
        return false;
130
    }
131
132
    /**
133
     * @param \ArrayIterator $migrations
134
     * @return int
135
     */
136
    public function getMaxMigrationVersion(\ArrayIterator $migrations)
137
    {
138
        $versions = [];
139
        foreach ($migrations as $migration) {
140
            $versions[] = $migration['version'];
141
        }
142
143
        sort($versions, SORT_NUMERIC);
144
        $versions = array_reverse($versions);
145
146
        return count($versions) > 0 ? $versions[0] : 0;
147
    }
148
149
    protected function applyMigration(array $migration, $down = false, $fake = false)
150
    {
151
        try {
152
            /** @var $migrationObject AbstractMigration */
153
            $migrationObject = new $migration['class']($this->serviceLocator);
154
155
            $this->console->writeLine(
156
                sprintf(
157
                    "%sExecute migration class %s %s.",
158
                    $fake ? '[FAKE] ' : '',
159
                    $migration['class'],
160
                    $down ? 'down' : 'up'
161
                )
162
            );
163
164
            if ($down) {
165
                $migrationObject->down();
166
                $this->versionTable->delete($migration['version']);
167
            } else {
168
                $migrationObject->up();
169
                $this->versionTable->save($migration['version']);
170
            }
171
        } catch (InvalidQueryException $e) {
172
            $previousMessage = $e->getPrevious() ? $e->getPrevious()->getMessage() : null;
173
            $msg = sprintf(
174
                '%s: "%s"; File: %s; Line #%d',
175
                $e->getMessage(),
176
                $previousMessage,
177
                $e->getFile(),
178
                $e->getLine()
179
            );
180
            throw new \Exception($msg, $e->getCode(), $e);
181
        } catch (\Exception $e) {
182
            $msg = sprintf('%s; File: %s; Line #%d', $e->getMessage(), $e->getFile(), $e->getLine());
183
            throw new \Exception($msg, $e->getCode(), $e);
184
        }
185
    }
186
}
187