Completed
Push — master ( 44c16e...180cba )
by max
01:59
created

Migration   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 169
Duplicated Lines 4.14 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 6
Bugs 0 Features 2
Metric Value
wmc 28
c 6
b 0
f 2
lcom 1
cbo 4
dl 7
loc 169
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
C migrate() 0 33 12
A sortMigrationsByVersionDesc() 7 16 3
A hasMigrationVersions() 0 10 3
A getMaxMigrationVersion() 0 12 3
B applyMigration() 0 36 6

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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\Version\Table;
11
use T4web\Migrations\Version\Resolver;
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 Resolver                 $versionResolver
36
     * @param Console                  $console
37
     * @param ServiceLocatorInterface  $serviceLocator
38
     * @throws \Exception
39
     */
40
    public function __construct(
41
        Resolver $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
     * @throws \Exception
57
     */
58
    public function migrate($version = null, $force = false, $down = false)
59
    {
60
        $migrations = $this->versionResolver->getAll($force);
61
62
        if (!is_null($version) && !$this->hasMigrationVersions($migrations, $version)) {
63
            throw new \Exception(sprintf('Migration version %s is not found!', $version));
64
        }
65
66
        $currentMigrationVersion = $this->versionTable->getCurrentVersion();
67
        if (!is_null($version) && $version == $currentMigrationVersion && !$force) {
68
            throw new \Exception(sprintf('Migration version %s is current version!', $version));
69
        }
70
71
        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...
72
            foreach ($migrations as $migration) {
73
                if ($migration['version'] == $version) {
74
                    // if existing migration is forced to apply - delete its information from migrated
75
                    // to avoid duplicate key error
76
                    if (!$down) {
77
                        $this->versionTable->delete($migration['version']);
78
                    }
79
                    $this->applyMigration($migration, $down);
80
                    break;
81
                }
82
            }
83
84
            return;
85
        }
86
87
        foreach ($this->versionResolver->getAll() as $migration) {
88
            $this->applyMigration($migration, false);
89
        }
90
    }
91
92
    /**
93
     * @param \ArrayIterator $migrations
94
     * @return \ArrayIterator
95
     */
96
    public function sortMigrationsByVersionDesc(\ArrayIterator $migrations)
97
    {
98
        $sortedMigrations = clone $migrations;
99
100
        $sortedMigrations->uasort(
101 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...
102
                if ($a['version'] == $b['version']) {
103
                    return 0;
104
                }
105
106
                return ($a['version'] > $b['version']) ? -1 : 1;
107
            }
108
        );
109
110
        return $sortedMigrations;
111
    }
112
113
    /**
114
     * Check migrations classes existence
115
     *
116
     * @param \ArrayIterator $migrations
117
     * @param int            $version
118
     * @return bool
119
     */
120
    public function hasMigrationVersions(\ArrayIterator $migrations, $version)
121
    {
122
        foreach ($migrations as $migration) {
123
            if ($migration['version'] == $version) {
124
                return true;
125
            }
126
        }
127
128
        return false;
129
    }
130
131
    /**
132
     * @param \ArrayIterator $migrations
133
     * @return int
134
     */
135
    public function getMaxMigrationVersion(\ArrayIterator $migrations)
136
    {
137
        $versions = [];
138
        foreach ($migrations as $migration) {
139
            $versions[] = $migration['version'];
140
        }
141
142
        sort($versions, SORT_NUMERIC);
143
        $versions = array_reverse($versions);
144
145
        return count($versions) > 0 ? $versions[0] : 0;
146
    }
147
148
    protected function applyMigration(array $migration, $down = false)
149
    {
150
        try {
151
            /** @var $migrationObject AbstractMigration */
152
            $migrationObject = new $migration['class']($this->serviceLocator);
153
154
            $this->console->writeLine(
155
                sprintf(
156
                    "%sExecute migration class %s.",
157
                    $migration['class'],
158
                    $down ? 'down' : 'up'
159
                )
160
            );
161
162
            if ($down) {
163
                $migrationObject->down();
164
                $this->versionTable->delete($migration['version']);
165
            } else {
166
                $migrationObject->up();
167
                $this->versionTable->save($migration['version']);
168
            }
169
        } catch (InvalidQueryException $e) {
170
            $previousMessage = $e->getPrevious() ? $e->getPrevious()->getMessage() : null;
171
            $msg = sprintf(
172
                '%s: "%s"; File: %s; Line #%d',
173
                $e->getMessage(),
174
                $previousMessage,
175
                $e->getFile(),
176
                $e->getLine()
177
            );
178
            throw new \Exception($msg, $e->getCode(), $e);
179
        } catch (\Exception $e) {
180
            $msg = sprintf('%s; File: %s; Line #%d', $e->getMessage(), $e->getFile(), $e->getLine());
181
            throw new \Exception($msg, $e->getCode(), $e);
182
        }
183
    }
184
}
185