Completed
Push — master ( 6e739b...0f594c )
by Asmir
22s queued 12s
created

MigrateCommand::getVersionNameFromAlias()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 12
c 0
b 0
f 0
nc 4
nop 1
dl 0
loc 23
ccs 13
cts 13
cp 1
crap 5
rs 9.5555
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\Migrations\Tools\Console\Command;
6
7
use Doctrine\Migrations\Exception\NoMigrationsFoundWithCriteria;
8
use Doctrine\Migrations\Exception\UnknownMigrationVersion;
9
use Doctrine\Migrations\Metadata\ExecutedMigrationsSet;
10
use Symfony\Component\Console\Formatter\OutputFormatter;
11
use Symfony\Component\Console\Input\InputArgument;
12
use Symfony\Component\Console\Input\InputInterface;
13
use Symfony\Component\Console\Input\InputOption;
14
use Symfony\Component\Console\Output\OutputInterface;
15
use function count;
16
use function getcwd;
17
use function is_string;
18
use function is_writable;
19
use function sprintf;
20
use function substr;
21
22
/**
23
 * The MigrateCommand class is responsible for executing a migration from the current version to another
24
 * version up or down. It will calculate all the migration versions that need to be executed and execute them.
25
 */
26
final class MigrateCommand extends DoctrineCommand
27
{
28
    /** @var string */
29
    protected static $defaultName = 'migrations:migrate';
30
31 15
    protected function configure() : void
32
    {
33
        $this
34 15
            ->setAliases(['migrate'])
35 15
            ->setDescription(
36 15
                'Execute a migration to a specified version or the latest available version.'
37
            )
38 15
            ->addArgument(
39 15
                'version',
40 15
                InputArgument::OPTIONAL,
41 15
                'The version FQCN or alias (first, prev, next, latest) to migrate to.',
42 15
                'latest'
43
            )
44 15
            ->addOption(
45 15
                'write-sql',
46 15
                null,
47 15
                InputOption::VALUE_OPTIONAL,
48 15
                'The path to output the migration SQL file instead of executing it. Defaults to current working directory.',
49 15
                false
50
            )
51 15
            ->addOption(
52 15
                'dry-run',
53 15
                null,
54 15
                InputOption::VALUE_NONE,
55 15
                'Execute the migration as a dry run.'
56
            )
57 15
            ->addOption(
58 15
                'query-time',
59 15
                null,
60 15
                InputOption::VALUE_NONE,
61 15
                'Time all the queries individually.'
62
            )
63 15
            ->addOption(
64 15
                'allow-no-migration',
65 15
                null,
66 15
                InputOption::VALUE_NONE,
67 15
                'Do not throw an exception if no migration is available.'
68
            )
69 15
            ->addOption(
70 15
                'all-or-nothing',
71 15
                null,
72 15
                InputOption::VALUE_OPTIONAL,
73 15
                'Wrap the entire migration in a transaction.',
74 15
                false
75
            )
76 15
            ->setHelp(<<<EOT
77 15
The <info>%command.name%</info> command executes a migration to a specified version or the latest available version:
78
79
    <info>%command.full_name%</info>
80
81
You can optionally manually specify the version you wish to migrate to:
82
83
    <info>%command.full_name% FQCN</info>
84
85
You can specify the version you wish to migrate to using an alias:
86
87
    <info>%command.full_name% prev</info>
88
    <info>These alias are defined : first, latest, prev, current and next</info>
89
90
You can specify the version you wish to migrate to using an number against the current version:
91
92
    <info>%command.full_name% current+3</info>
93
94
You can also execute the migration as a <comment>--dry-run</comment>:
95
96
    <info>%command.full_name% FQCN --dry-run</info>
97
98
You can output the would be executed SQL statements to a file with <comment>--write-sql</comment>:
99
100
    <info>%command.full_name% FQCN --write-sql</info>
101
102
Or you can also execute the migration without a warning message which you need to interact with:
103
104
    <info>%command.full_name% --no-interaction</info>
105
106
You can also time all the different queries if you wanna know which one is taking so long:
107
108
    <info>%command.full_name% --query-time</info>
109
110
Use the --all-or-nothing option to wrap the entire migration in a transaction.
111
EOT
112
            );
113
114 15
        parent::configure();
115 15
    }
116
117 15
    protected function execute(InputInterface $input, OutputInterface $output) : int
118
    {
119 15
        $migratorConfigurationFactory = $this->getDependencyFactory()->getConsoleInputMigratorConfigurationFactory();
120 15
        $migratorConfiguration        = $migratorConfigurationFactory->getMigratorConfiguration($input);
121
122 15
        $question = 'WARNING! You are about to execute a database migration that could result in schema changes and data loss. Are you sure you wish to continue?';
123 15
        if (! $migratorConfiguration->isDryRun() && ! $this->canExecute($question, $input)) {
124 3
            $this->io->error('Migration cancelled!');
125
126 3
            return 3;
127
        }
128
129 12
        $this->getDependencyFactory()->getMetadataStorage()->ensureInitialized();
130
131 12
        $allowNoMigration = $input->getOption('allow-no-migration');
132 12
        $versionAlias     = $input->getArgument('version');
133 12
        $path             = $input->getOption('write-sql');
134
135
        try {
136 12
            $version = $this->getDependencyFactory()->getVersionAliasResolver()->resolveVersionAlias($versionAlias);
0 ignored issues
show
Bug introduced by
It seems like $versionAlias can also be of type null and string[]; however, parameter $alias of Doctrine\Migrations\Vers...::resolveVersionAlias() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

136
            $version = $this->getDependencyFactory()->getVersionAliasResolver()->resolveVersionAlias(/** @scrutinizer ignore-type */ $versionAlias);
Loading history...
137 2
        } catch (UnknownMigrationVersion|NoMigrationsFoundWithCriteria $e) {
138 2
            $this->getVersionNameFromAlias($versionAlias);
0 ignored issues
show
Bug introduced by
It seems like $versionAlias can also be of type null and string[]; however, parameter $versionAlias of Doctrine\Migrations\Tool...tVersionNameFromAlias() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

138
            $this->getVersionNameFromAlias(/** @scrutinizer ignore-type */ $versionAlias);
Loading history...
139
140 2
            return 1;
141
        }
142
143 10
        $planCalculator                = $this->getDependencyFactory()->getMigrationPlanCalculator();
144 10
        $statusCalculator              = $this->getDependencyFactory()->getMigrationStatusCalculator();
145 10
        $executedUnavailableMigrations = $statusCalculator->getExecutedUnavailableMigrations();
146
147 10
        if ($this->checkExecutedUnavailableMigrations($executedUnavailableMigrations, $input) === false) {
148 1
            return 3;
149
        }
150
151 9
        $plan = $planCalculator->getPlanUntilVersion($version);
152
153 9
        if (count($plan) === 0 && ! $allowNoMigration) {
154 1
            $this->io->warning('Could not find any migrations to execute.');
155
156 1
            return 1;
157
        }
158
159 8
        if (count($plan) === 0) {
160 2
            $this->getVersionNameFromAlias($versionAlias);
161
162 2
            return 0;
163
        }
164
165 6
        $migrator = $this->getDependencyFactory()->getMigrator();
166 6
        if ($migratorConfiguration->isDryRun()) {
167 2
            $sql = $migrator->migrate($plan, $migratorConfiguration);
168
169 2
            $path = is_string($path) ? $path : getcwd();
170
171 2
            if (! is_string($path) || ! is_writable($path)) {
0 ignored issues
show
introduced by
The condition is_string($path) is always true.
Loading history...
172
                $this->io->error('Path not writeable!');
173
174
                return 1;
175
            }
176
177 2
            $writer = $this->getDependencyFactory()->getQueryWriter();
178 2
            $writer->write($path, $plan->getDirection(), $sql);
179
180 2
            return 0;
181
        }
182
183 4
        $this->getDependencyFactory()->getLogger()->notice(
184 4
            'Migrating' . ($migratorConfiguration->isDryRun() ? ' (dry-run)' : '') . ' {direction} to {to}',
185
            [
186 4
                'direction' => $plan->getDirection(),
187 4
                'to' => (string) $version,
188
            ]
189
        );
190
191 4
        $migrator->migrate($plan, $migratorConfiguration);
192
193 4
        $this->io->newLine();
194
195 4
        return 0;
196
    }
197
198 10
    private function checkExecutedUnavailableMigrations(
199
        ExecutedMigrationsSet $executedUnavailableMigrations,
200
        InputInterface $input
201
    ) : bool {
202 10
        if (count($executedUnavailableMigrations) !== 0) {
203 1
            $this->io->warning(sprintf(
204 1
                'You have %s previously executed migrations in the database that are not registered migrations.',
205 1
                count($executedUnavailableMigrations)
206
            ));
207
208 1
            foreach ($executedUnavailableMigrations->getItems() as $executedUnavailableMigration) {
209 1
                $this->io->text(sprintf(
210 1
                    '<comment>>></comment> %s (<comment>%s</comment>)',
211 1
                    $executedUnavailableMigration->getExecutedAt() !== null
212
                        ? $executedUnavailableMigration->getExecutedAt()->format('Y-m-d H:i:s')
213 1
                        : null,
214 1
                    $executedUnavailableMigration->getVersion()
215
                ));
216
            }
217
218 1
            $question = 'Are you sure you wish to continue?';
219
220 1
            if (! $this->canExecute($question, $input)) {
221 1
                $this->io->error('Migration cancelled!');
222
223 1
                return false;
224
            }
225
        }
226
227 9
        return true;
228
    }
229
230 4
    private function getVersionNameFromAlias(string $versionAlias) : void
231
    {
232 4
        if ($versionAlias === 'first') {
233 1
            $this->io->error('Already at first version.');
234
235 1
            return;
236
        }
237
238 3
        if ($versionAlias === 'next' || $versionAlias === 'latest') {
239 1
            $this->io->error('Already at latest version.');
240
241 1
            return;
242
        }
243
244 2
        if (substr($versionAlias, 0, 7) === 'current') {
245 1
            $this->io->error('The delta couldn\'t be reached.');
246
247 1
            return;
248
        }
249
250 1
        $this->io->error(sprintf(
251 1
            'Unknown version: %s',
252 1
            OutputFormatter::escape($versionAlias)
253
        ));
254 1
    }
255
}
256