Completed
Push — master ( 178c75...b82d68 )
by Luís
11s
created

Migration::migrate()   C

Complexity

Conditions 15
Paths 42

Size

Total Lines 78
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 37
CRAP Score 15.004

Importance

Changes 0
Metric Value
dl 0
loc 78
ccs 37
cts 38
cp 0.9737
rs 5.15
c 0
b 0
f 0
cc 15
eloc 38
nc 42
nop 4
crap 15.004

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the LGPL. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\DBAL\Migrations;
21
22
use Doctrine\DBAL\Migrations\Configuration\Configuration;
23
use Doctrine\DBAL\Migrations\Event\MigrationsEventArgs;
24
25
/**
26
 * Class for running migrations to the current version or a manually specified version.
27
 *
28
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
29
 * @link        www.doctrine-project.org
30
 * @since       2.0
31
 * @author      Jonathan H. Wage <[email protected]>
32
 */
33
class Migration
34
{
35
    /**
36
     * The OutputWriter object instance used for outputting information
37
     *
38
     * @var OutputWriter
39
     */
40
    private $outputWriter;
41
42
    /**
43
     * @var Configuration
44
     */
45
    private $configuration;
46
47
    /**
48
     * @var boolean
49
     */
50
    private $noMigrationException;
51
52
    /**
53
     * Construct a Migration instance
54
     *
55
     * @param Configuration $configuration A migration Configuration instance
56
     */
57 37
    public function __construct(Configuration $configuration)
58
    {
59 37
        $this->configuration = $configuration;
60 37
        $this->outputWriter = $configuration->getOutputWriter();
61 37
        $this->noMigrationException = false;
62 37
    }
63
64
    /**
65
     * Get the array of versions and SQL queries that would be executed for
66
     * each version but do not execute anything.
67
     *
68
     * @param string $to The version to migrate to.
69
     *
70
     * @return array $sql  The array of SQL queries.
71
     */
72 2
    public function getSql($to = null)
73
    {
74 2
        return $this->migrate($to, true);
75
    }
76
77
    /**
78
     * Write a migration SQL file to the given path
79
     *
80
     * @param string $path The path to write the migration SQL file.
81
     * @param string $to   The version to migrate to.
82
     *
83
     * @return boolean $written
84
     */
85 6
    public function writeSqlFile($path, $to = null)
86
    {
87 6
        $sql = $this->getSql($to);
88
89 6
        $from = $this->configuration->getCurrentVersion();
90 6
        if ($to === null) {
91 1
            $to = $this->configuration->getLatestVersion();
92
        }
93
94 6
        $direction = $from > $to ? Version::DIRECTION_DOWN : Version::DIRECTION_UP;
95
96 6
        $this->outputWriter->write(sprintf("-- Migrating from %s to %s\n", $from, $to));
97
98 6
        $sqlWriter = new SqlFileWriter(
99 6
            $this->configuration->getMigrationsColumnName(),
100 6
            $this->configuration->getMigrationsTableName(),
101 6
            $path,
102 6
            $this->outputWriter
103
        );
104
105 6
        return $sqlWriter->write($sql, $direction);
106
    }
107
108
    /**
109
     * @param boolean $noMigrationException Throw an exception or not if no migration is found. Mostly for Continuous Integration.
110
     */
111 2
    public function setNoMigrationException($noMigrationException = false)
112
    {
113 2
        $this->noMigrationException = $noMigrationException;
114 2
    }
115
116
    /**
117
     * Run a migration to the current version or the given target version.
118
     *
119
     * @param string  $to             The version to migrate to.
120
     * @param boolean $dryRun         Whether or not to make this a dry run and not execute anything.
121
     * @param boolean $timeAllQueries Measuring or not the execution time of each SQL query.
122
     * @param callable|null $confirm A callback to confirm whether the migrations should be executed.
123
     *
124
     * @return array An array of migration sql statements. This will be empty if the the $confirm callback declines to execute the migration
125
     *
126
     * @throws MigrationException
127
     */
128 31
    public function migrate($to = null, $dryRun = false, $timeAllQueries = false, callable $confirm = null)
129
    {
130
        /**
131
         * If no version to migrate to is given we default to the last available one.
132
         */
133 31
        if ($to === null) {
134 14
            $to = $this->configuration->getLatestVersion();
135
        }
136
137 31
        $from = (string) $this->configuration->getCurrentVersion();
138 31
        $to   = (string) $to;
139
140
        /**
141
         * Throw an error if we can't find the migration to migrate to in the registered
142
         * migrations.
143
         */
144 31
        $migrations = $this->configuration->getMigrations();
145 31
        if (!isset($migrations[$to]) && $to > 0) {
146 1
            throw MigrationException::unknownMigrationVersion($to);
147
        }
148
149 30
        $direction = $from > $to ? Version::DIRECTION_DOWN : Version::DIRECTION_UP;
150 30
        $migrationsToExecute = $this->configuration->getMigrationsToExecute($direction, $to);
151
152
        /**
153
         * If
154
         *  there are no migrations to execute
155
         *  and there are migrations,
156
         *  and the migration from and to are the same
157
         * means we are already at the destination return an empty array()
158
         * to signify that there is nothing left to do.
159
         */
160 30
        if ($from === $to && empty($migrationsToExecute) && !empty($migrations)) {
161 2
            return $this->noMigrations();
162
        }
163
164 29
        if (!$dryRun && false === $this->migrationsCanExecute($confirm)) {
165 1
            return [];
166
        }
167
168 28
        $output = $dryRun ? 'Executing dry run of migration' : 'Migrating';
169 28
        $output .= ' <info>%s</info> to <comment>%s</comment> from <comment>%s</comment>';
170 28
        $this->outputWriter->write(sprintf($output, $direction, $to, $from));
171
172
        /**
173
         * If there are no migrations to execute throw an exception.
174
         */
175 28
        if (empty($migrationsToExecute) && !$this->noMigrationException) {
176 1
            throw MigrationException::noMigrationsToExecute();
177
        } elseif (empty($migrationsToExecute)) {
178 1
            return $this->noMigrations();
179
        }
180
181 26
        $this->configuration->dispatchEvent(
182 26
            Events::onMigrationsMigrating,
183 26
            new MigrationsEventArgs($this->configuration, $direction, $dryRun)
184
        );
185
186 26
        $sql = [];
187 26
        $time = 0;
188 26
        foreach ($migrationsToExecute as $version) {
189 26
            $versionSql = $version->execute($direction, $dryRun, $timeAllQueries);
190 26
            $sql[$version->getVersion()] = $versionSql;
191 26
            $time += $version->getTime();
192
        }
193
194 26
        $this->configuration->dispatchEvent(
195 26
            Events::onMigrationsMigrated,
196 26
            new MigrationsEventArgs($this->configuration, $direction, $dryRun)
197
        );
198
199 26
        $this->outputWriter->write("\n  <comment>------------------------</comment>\n");
200 26
        $this->outputWriter->write(sprintf("  <info>++</info> finished in %ss", $time));
201 26
        $this->outputWriter->write(sprintf("  <info>++</info> %s migrations executed", count($migrationsToExecute)));
202 26
        $this->outputWriter->write(sprintf("  <info>++</info> %s sql queries", count($sql, true) - count($sql)));
203
204 26
        return $sql;
205
    }
206
207 3
    private function noMigrations()
208
    {
209 3
        $this->outputWriter->write('<comment>No migrations to execute.</comment>');
210 3
        return [];
211
    }
212
213 27
    private function migrationsCanExecute(callable $confirm=null)
214
    {
215 27
        return null === $confirm ? true : $confirm();
216
    }
217
}
218