Completed
Push — 2.1-master-merge ( 240673 )
by Alexander
13:45
created

BaseMigrateController::actionFresh()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.243

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 7
cts 10
cp 0.7
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 3
nop 0
crap 3.243
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\console\controllers;
9
10
use Yii;
11
use yii\base\InvalidConfigException;
12
use yii\base\NotSupportedException;
13
use yii\console\Controller;
14
use yii\console\Exception;
15
use yii\console\ExitCode;
16
use yii\helpers\Console;
17
use yii\helpers\FileHelper;
18
19
/**
20
 * BaseMigrateController is the base class for migrate controllers.
21
 *
22
 * @author Qiang Xue <[email protected]>
23
 * @since 2.0
24
 */
25
abstract class BaseMigrateController extends Controller
26
{
27
    /**
28
     * The name of the dummy migration that marks the beginning of the whole migration history.
29
     */
30
    const BASE_MIGRATION = 'm000000_000000_base';
31
32
    /**
33
     * @var string the default command action.
34
     */
35
    public $defaultAction = 'up';
36
    /**
37
     * @var string|array the directory containing the migration classes. This can be either
38
     * a [path alias](guide:concept-aliases) or a directory path.
39
     *
40
     * Migration classes located at this path should be declared without a namespace.
41
     * Use [[migrationNamespaces]] property in case you are using namespaced migrations.
42
     *
43
     * If you have set up [[migrationNamespaces]], you may set this field to `null` in order
44
     * to disable usage of migrations that are not namespaced.
45
     *
46
     * Since version 2.0.12 you may also specify an array of migration paths that should be searched for
47
     * migrations to load. This is mainly useful to support old extensions that provide migrations
48
     * without namespace and to adopt the new feature of namespaced migrations while keeping existing migrations.
49
     *
50
     * In general, to load migrations from different locations, [[migrationNamespaces]] is the preferable solution
51
     * as the migration name contains the origin of the migration in the history, which is not the case when
52
     * using multiple migration paths.
53
     *
54
     * @see $migrationNamespaces
55
     */
56
    public $migrationPath = ['@app/migrations'];
57
    /**
58
     * @var array list of namespaces containing the migration classes.
59
     *
60
     * Migration namespaces should be resolvable as a [path alias](guide:concept-aliases) if prefixed with `@`, e.g. if you specify
61
     * the namespace `app\migrations`, the code `Yii::getAlias('@app/migrations')` should be able to return
62
     * the file path to the directory this namespace refers to.
63
     * This corresponds with the [autoloading conventions](guide:concept-autoloading) of Yii.
64
     *
65
     * For example:
66
     *
67
     * ```php
68
     * [
69
     *     'app\migrations',
70
     *     'some\extension\migrations',
71
     * ]
72
     * ```
73
     *
74
     * @since 2.0.10
75
     * @see $migrationPath
76
     */
77
    public $migrationNamespaces = [];
78
    /**
79
     * @var string the template file for generating new migrations.
80
     * This can be either a [path alias](guide:concept-aliases) (e.g. "@app/migrations/template.php")
81
     * or a file path.
82
     */
83
    public $templateFile;
84
85
    /**
86
     * @var bool indicates whether the console output should be compacted.
87
     * If this is set to true, the individual commands ran within the migration will not be output to the console.
88
     * Default is false, in other words the output is fully verbose by default.
89
     * @since 2.0.13
90
     */
91
    public $compact = false;
92
93
    /**
94
     * @inheritdoc
95
     */
96 24
    public function options($actionID)
97
    {
98 24
        return array_merge(
99 24
            parent::options($actionID),
100 24
            ['migrationPath', 'migrationNamespaces', 'compact'], // global for all actions
101 24
            $actionID === 'create' ? ['templateFile'] : [] // action create
102
        );
103
    }
104
105
    /**
106
     * This method is invoked right before an action is to be executed (after all possible filters.)
107
     * It checks the existence of the [[migrationPath]].
108
     * @param \yii\base\Action $action the action to be executed.
109
     * @throws InvalidConfigException if directory specified in migrationPath doesn't exist and action isn't "create".
110
     * @return bool whether the action should continue to be executed.
111
     */
112 33
    public function beforeAction($action)
113
    {
114 33
        if (parent::beforeAction($action)) {
115 33
            if (empty($this->migrationNamespaces) && empty($this->migrationPath)) {
116
                throw new InvalidConfigException('At least one of `migrationPath` or `migrationNamespaces` should be specified.');
117
            }
118
119 33
            foreach ($this->migrationNamespaces as $key => $value) {
120 8
                $this->migrationNamespaces[$key] = trim($value, '\\');
121
            }
122
123 33
            if (is_array($this->migrationPath)) {
124 7
                foreach ($this->migrationPath as $i => $path) {
125 7
                    $this->migrationPath[$i] = Yii::getAlias($path);
126
                }
127 26
            } elseif ($this->migrationPath !== null) {
128 20
                $path = Yii::getAlias($this->migrationPath);
129 20
                if (!is_dir($path)) {
130 5
                    if ($action->id !== 'create') {
131
                        throw new InvalidConfigException("Migration failed. Directory specified in migrationPath doesn't exist: {$this->migrationPath}");
132
                    }
133 5
                    FileHelper::createDirectory($path);
0 ignored issues
show
Bug introduced by
It seems like $path defined by \Yii::getAlias($this->migrationPath) on line 128 can also be of type boolean; however, yii\helpers\BaseFileHelper::createDirectory() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
134
                }
135 20
                $this->migrationPath = $path;
0 ignored issues
show
Documentation Bug introduced by
It seems like $path can also be of type boolean. However, the property $migrationPath is declared as type string|array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
136
            }
137
138 33
            $version = Yii::getVersion();
139 33
            $this->stdout("Yii Migration Tool (based on Yii v{$version})\n\n");
140
141 33
            return true;
142
        }
143
144
        return false;
145
    }
146
147
    /**
148
     * Upgrades the application by applying new migrations.
149
     *
150
     * For example,
151
     *
152
     * ```
153
     * yii migrate     # apply all new migrations
154
     * yii migrate 3   # apply the first 3 new migrations
155
     * ```
156
     *
157
     * @param int $limit the number of new migrations to be applied. If 0, it means
158
     * applying all available new migrations.
159
     *
160
     * @return int the status of the action execution. 0 means normal, other values mean abnormal.
161
     */
162 22
    public function actionUp($limit = 0)
163
    {
164 22
        $migrations = $this->getNewMigrations();
165 22
        if (empty($migrations)) {
166 1
            $this->stdout("No new migrations found. Your system is up-to-date.\n", Console::FG_GREEN);
167
168 1
            return ExitCode::OK;
169
        }
170
171 21
        $total = count($migrations);
172 21
        $limit = (int) $limit;
173 21
        if ($limit > 0) {
174 4
            $migrations = array_slice($migrations, 0, $limit);
175
        }
176
177 21
        $n = count($migrations);
178 21
        if ($n === $total) {
179 20
            $this->stdout("Total $n new " . ($n === 1 ? 'migration' : 'migrations') . " to be applied:\n", Console::FG_YELLOW);
180
        } else {
181 2
            $this->stdout("Total $n out of $total new " . ($total === 1 ? 'migration' : 'migrations') . " to be applied:\n", Console::FG_YELLOW);
182
        }
183
184 21
        foreach ($migrations as $migration) {
185 21
            $this->stdout("\t$migration\n");
186
        }
187 21
        $this->stdout("\n");
188
189 21
        $applied = 0;
190 21
        if ($this->confirm('Apply the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) {
191 21
            foreach ($migrations as $migration) {
192 21
                if (!$this->migrateUp($migration)) {
193
                    $this->stdout("\n$applied from $n " . ($applied === 1 ? 'migration was' : 'migrations were') . " applied.\n", Console::FG_RED);
194
                    $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
195
196
                    return ExitCode::UNSPECIFIED_ERROR;
197
                }
198 21
                $applied++;
199
            }
200
201 21
            $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " applied.\n", Console::FG_GREEN);
202 21
            $this->stdout("\nMigrated up successfully.\n", Console::FG_GREEN);
203
        }
204 21
    }
205
206
    /**
207
     * Downgrades the application by reverting old migrations.
208
     *
209
     * For example,
210
     *
211
     * ```
212
     * yii migrate/down     # revert the last migration
213
     * yii migrate/down 3   # revert the last 3 migrations
214
     * yii migrate/down all # revert all migrations
215
     * ```
216
     *
217
     * @param int|string $limit the number of migrations to be reverted. Defaults to 1,
218
     * meaning the last applied migration will be reverted. When value is "all", all migrations will be reverted.
219
     * @throws Exception if the number of the steps specified is less than 1.
220
     *
221
     * @return int the status of the action execution. 0 means normal, other values mean abnormal.
222
     */
223 11
    public function actionDown($limit = 1)
224
    {
225 11
        if ($limit === 'all') {
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison === seems to always evaluate to false as the types of $limit (integer) and 'all' (string) can never be identical. Maybe you want to use a loose comparison == instead?
Loading history...
226 1
            $limit = null;
227
        } else {
228 10
            $limit = (int) $limit;
229 10
            if ($limit < 1) {
230
                throw new Exception('The step argument must be greater than 0.');
231
            }
232
        }
233
234 11
        $migrations = $this->getMigrationHistory($limit);
235
236 11
        if (empty($migrations)) {
237
            $this->stdout("No migration has been done before.\n", Console::FG_YELLOW);
238
239
            return ExitCode::OK;
240
        }
241
242 11
        $migrations = array_keys($migrations);
243
244 11
        $n = count($migrations);
245 11
        $this->stdout("Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be reverted:\n", Console::FG_YELLOW);
246 11
        foreach ($migrations as $migration) {
247 11
            $this->stdout("\t$migration\n");
248
        }
249 11
        $this->stdout("\n");
250
251 11
        $reverted = 0;
252 11
        if ($this->confirm('Revert the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) {
253 11
            foreach ($migrations as $migration) {
254 11
                if (!$this->migrateDown($migration)) {
255
                    $this->stdout("\n$reverted from $n " . ($reverted === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_RED);
256
                    $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
257
258
                    return ExitCode::UNSPECIFIED_ERROR;
259
                }
260 11
                $reverted++;
261
            }
262 11
            $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_GREEN);
263 11
            $this->stdout("\nMigrated down successfully.\n", Console::FG_GREEN);
264
        }
265 11
    }
266
267
    /**
268
     * Redoes the last few migrations.
269
     *
270
     * This command will first revert the specified migrations, and then apply
271
     * them again. For example,
272
     *
273
     * ```
274
     * yii migrate/redo     # redo the last applied migration
275
     * yii migrate/redo 3   # redo the last 3 applied migrations
276
     * yii migrate/redo all # redo all migrations
277
     * ```
278
     *
279
     * @param int|string $limit the number of migrations to be redone. Defaults to 1,
280
     * meaning the last applied migration will be redone. When equals "all", all migrations will be redone.
281
     * @throws Exception if the number of the steps specified is less than 1.
282
     *
283
     * @return int the status of the action execution. 0 means normal, other values mean abnormal.
284
     */
285 2
    public function actionRedo($limit = 1)
286
    {
287 2
        if ($limit === 'all') {
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison === seems to always evaluate to false as the types of $limit (integer) and 'all' (string) can never be identical. Maybe you want to use a loose comparison == instead?
Loading history...
288
            $limit = null;
289
        } else {
290 2
            $limit = (int) $limit;
291 2
            if ($limit < 1) {
292
                throw new Exception('The step argument must be greater than 0.');
293
            }
294
        }
295
296 2
        $migrations = $this->getMigrationHistory($limit);
297
298 2
        if (empty($migrations)) {
299
            $this->stdout("No migration has been done before.\n", Console::FG_YELLOW);
300
301
            return ExitCode::OK;
302
        }
303
304 2
        $migrations = array_keys($migrations);
305
306 2
        $n = count($migrations);
307 2
        $this->stdout("Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be redone:\n", Console::FG_YELLOW);
308 2
        foreach ($migrations as $migration) {
309 2
            $this->stdout("\t$migration\n");
310
        }
311 2
        $this->stdout("\n");
312
313 2
        if ($this->confirm('Redo the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) {
314 2
            foreach ($migrations as $migration) {
315 2
                if (!$this->migrateDown($migration)) {
316
                    $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
317
318 2
                    return ExitCode::UNSPECIFIED_ERROR;
319
                }
320
            }
321 2
            foreach (array_reverse($migrations) as $migration) {
322 2
                if (!$this->migrateUp($migration)) {
323
                    $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
324
325 2
                    return ExitCode::UNSPECIFIED_ERROR;
326
                }
327
            }
328 2
            $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " redone.\n", Console::FG_GREEN);
329 2
            $this->stdout("\nMigration redone successfully.\n", Console::FG_GREEN);
330
        }
331 2
    }
332
333
    /**
334
     * Upgrades or downgrades till the specified version.
335
     *
336
     * Can also downgrade versions to the certain apply time in the past by providing
337
     * a UNIX timestamp or a string parseable by the strtotime() function. This means
338
     * that all the versions applied after the specified certain time would be reverted.
339
     *
340
     * This command will first revert the specified migrations, and then apply
341
     * them again. For example,
342
     *
343
     * ```
344
     * yii migrate/to 101129_185401                          # using timestamp
345
     * yii migrate/to m101129_185401_create_user_table       # using full name
346
     * yii migrate/to 1392853618                             # using UNIX timestamp
347
     * yii migrate/to "2014-02-15 13:00:50"                  # using strtotime() parseable string
348
     * yii migrate/to app\migrations\M101129185401CreateUser # using full namespace name
349
     * ```
350
     *
351
     * @param string $version either the version name or the certain time value in the past
352
     * that the application should be migrated to. This can be either the timestamp,
353
     * the full name of the migration, the UNIX timestamp, or the parseable datetime
354
     * string.
355
     * @throws Exception if the version argument is invalid.
356
     */
357 3
    public function actionTo($version)
358
    {
359 3
        if (($namespaceVersion = $this->extractNamespaceMigrationVersion($version)) !== false) {
360 1
            $this->migrateToVersion($namespaceVersion);
361 2
        } elseif (($migrationName = $this->extractMigrationVersion($version)) !== false) {
362 2
            $this->migrateToVersion($migrationName);
363
        } elseif ((string) (int) $version == $version) {
364
            $this->migrateToTime($version);
365
        } elseif (($time = strtotime($version)) !== false) {
366
            $this->migrateToTime($time);
367
        } else {
368
            throw new Exception("The version argument must be either a timestamp (e.g. 101129_185401),\n the full name of a migration (e.g. m101129_185401_create_user_table),\n the full namespaced name of a migration (e.g. app\\migrations\\M101129185401CreateUserTable),\n a UNIX timestamp (e.g. 1392853000), or a datetime string parseable\nby the strtotime() function (e.g. 2014-02-15 13:00:50).");
369
        }
370 3
    }
371
372
    /**
373
     * Modifies the migration history to the specified version.
374
     *
375
     * No actual migration will be performed.
376
     *
377
     * ```
378
     * yii migrate/mark 101129_185401                        # using timestamp
379
     * yii migrate/mark m101129_185401_create_user_table     # using full name
380
     * yii migrate/mark app\migrations\M101129185401CreateUser # using full namespace name
381
     * yii migrate/mark m000000_000000_base # reset the complete migration history
382
     * ```
383
     *
384
     * @param string $version the version at which the migration history should be marked.
385
     * This can be either the timestamp or the full name of the migration.
386
     * You may specify the name `m000000_000000_base` to set the migration history to a
387
     * state where no migration has been applied.
388
     * @return int CLI exit code
389
     * @throws Exception if the version argument is invalid or the version cannot be found.
390
     */
391 4
    public function actionMark($version)
392
    {
393 4
        $originalVersion = $version;
394 4
        if (($namespaceVersion = $this->extractNamespaceMigrationVersion($version)) !== false) {
395 1
            $version = $namespaceVersion;
396 3
        } elseif (($migrationName = $this->extractMigrationVersion($version)) !== false) {
397 3
            $version = $migrationName;
398
        } elseif ($version !== static::BASE_MIGRATION) {
399
            throw new Exception("The version argument must be either a timestamp (e.g. 101129_185401)\nor the full name of a migration (e.g. m101129_185401_create_user_table)\nor the full name of a namespaced migration (e.g. app\\migrations\\M101129185401CreateUserTable).");
400
        }
401
402
        // try mark up
403 4
        $migrations = $this->getNewMigrations();
404 4
        foreach ($migrations as $i => $migration) {
405 3
            if (strpos($migration, $version) === 0) {
406 3
                if ($this->confirm("Set migration history at $originalVersion?")) {
407 3
                    for ($j = 0; $j <= $i; ++$j) {
408 3
                        $this->addMigrationHistory($migrations[$j]);
409
                    }
410 3
                    $this->stdout("The migration history is set at $originalVersion.\nNo actual migration was performed.\n", Console::FG_GREEN);
411
                }
412
413 3
                return ExitCode::OK;
414
            }
415
        }
416
417
        // try mark down
418 1
        $migrations = array_keys($this->getMigrationHistory(null));
419 1
        $migrations[] = static::BASE_MIGRATION;
420 1
        foreach ($migrations as $i => $migration) {
421 1
            if (strpos($migration, $version) === 0) {
422 1
                if ($i === 0) {
423
                    $this->stdout("Already at '$originalVersion'. Nothing needs to be done.\n", Console::FG_YELLOW);
424
                } else {
425 1
                    if ($this->confirm("Set migration history at $originalVersion?")) {
426 1
                        for ($j = 0; $j < $i; ++$j) {
427 1
                            $this->removeMigrationHistory($migrations[$j]);
428
                        }
429 1
                        $this->stdout("The migration history is set at $originalVersion.\nNo actual migration was performed.\n", Console::FG_GREEN);
430
                    }
431
                }
432
433 1
                return ExitCode::OK;
434
            }
435
        }
436
437
        throw new Exception("Unable to find the version '$originalVersion'.");
438
    }
439
440
    /**
441
     * Truncates the whole database and starts the migration from the beginning.
442
     *
443
     * ```
444
     * yii migrate/fresh
445
     * ```
446
     *
447
     * @since 2.0.13
448
     */
449 1
    public function actionFresh()
450
    {
451 1
        if (YII_ENV_PROD) {
452
            $this->stdout("YII_ENV is set to 'prod'.\nRefreshing migrations is not possible on production systems.\n");
453
            return ExitCode::OK;
454
        }
455
456 1
        if ($this->confirm(
457 1
            "Are you sure you want to reset the database and start the migration from the beginning?\nAll data will be lost irreversibly!")) {
458 1
            $this->truncateDatabase();
459 1
            $this->actionUp();
460
        } else {
461
            $this->stdout('Action was cancelled by user. Nothing has been performed.');
462
        }
463 1
    }
464
465
    /**
466
     * Checks if given migration version specification matches namespaced migration name.
467
     * @param string $rawVersion raw version specification received from user input.
468
     * @return string|false actual migration version, `false` - if not match.
469
     * @since 2.0.10
470
     */
471 6
    private function extractNamespaceMigrationVersion($rawVersion)
472
    {
473 6
        if (preg_match('/^\\\\?([\w_]+\\\\)+m(\d{6}_?\d{6})(\D.*)?$/is', $rawVersion, $matches)) {
474 2
            return trim($rawVersion, '\\');
475
        }
476
477 4
        return false;
478
    }
479
480
    /**
481
     * Checks if given migration version specification matches migration base name.
482
     * @param string $rawVersion raw version specification received from user input.
483
     * @return string|false actual migration version, `false` - if not match.
484
     * @since 2.0.10
485
     */
486 4
    private function extractMigrationVersion($rawVersion)
487
    {
488 4
        if (preg_match('/^m?(\d{6}_?\d{6})(\D.*)?$/is', $rawVersion, $matches)) {
489 4
            return 'm' . $matches[1];
490
        }
491
492
        return false;
493
    }
494
495
    /**
496
     * Displays the migration history.
497
     *
498
     * This command will show the list of migrations that have been applied
499
     * so far. For example,
500
     *
501
     * ```
502
     * yii migrate/history     # showing the last 10 migrations
503
     * yii migrate/history 5   # showing the last 5 migrations
504
     * yii migrate/history all # showing the whole history
505
     * ```
506
     *
507
     * @param int|string $limit the maximum number of migrations to be displayed.
508
     * If it is "all", the whole migration history will be displayed.
509
     * @throws \yii\console\Exception if invalid limit value passed
510
     */
511 4
    public function actionHistory($limit = 10)
512
    {
513 4
        if ($limit === 'all') {
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison === seems to always evaluate to false as the types of $limit (integer) and 'all' (string) can never be identical. Maybe you want to use a loose comparison == instead?
Loading history...
514
            $limit = null;
515
        } else {
516 4
            $limit = (int) $limit;
517 4
            if ($limit < 1) {
518
                throw new Exception('The limit must be greater than 0.');
519
            }
520
        }
521
522 4
        $migrations = $this->getMigrationHistory($limit);
523
524 4
        if (empty($migrations)) {
525 4
            $this->stdout("No migration has been done before.\n", Console::FG_YELLOW);
526
        } else {
527 2
            $n = count($migrations);
528 2
            if ($limit > 0) {
529 2
                $this->stdout("Showing the last $n applied " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
530
            } else {
531
                $this->stdout("Total $n " . ($n === 1 ? 'migration has' : 'migrations have') . " been applied before:\n", Console::FG_YELLOW);
532
            }
533 2
            foreach ($migrations as $version => $time) {
534 2
                $this->stdout("\t(" . date('Y-m-d H:i:s', $time) . ') ' . $version . "\n");
535
            }
536
        }
537 4
    }
538
539
    /**
540
     * Displays the un-applied new migrations.
541
     *
542
     * This command will show the new migrations that have not been applied.
543
     * For example,
544
     *
545
     * ```
546
     * yii migrate/new     # showing the first 10 new migrations
547
     * yii migrate/new 5   # showing the first 5 new migrations
548
     * yii migrate/new all # showing all new migrations
549
     * ```
550
     *
551
     * @param int|string $limit the maximum number of new migrations to be displayed.
552
     * If it is `all`, all available new migrations will be displayed.
553
     * @throws \yii\console\Exception if invalid limit value passed
554
     */
555 1
    public function actionNew($limit = 10)
556
    {
557 1
        if ($limit === 'all') {
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison === seems to always evaluate to false as the types of $limit (integer) and 'all' (string) can never be identical. Maybe you want to use a loose comparison == instead?
Loading history...
558
            $limit = null;
559
        } else {
560 1
            $limit = (int) $limit;
561 1
            if ($limit < 1) {
562
                throw new Exception('The limit must be greater than 0.');
563
            }
564
        }
565
566 1
        $migrations = $this->getNewMigrations();
567
568 1
        if (empty($migrations)) {
569 1
            $this->stdout("No new migrations found. Your system is up-to-date.\n", Console::FG_GREEN);
570
        } else {
571 1
            $n = count($migrations);
572 1
            if ($limit && $n > $limit) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $limit of type null|integer 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...
573
                $migrations = array_slice($migrations, 0, $limit);
574
                $this->stdout("Showing $limit out of $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
575
            } else {
576 1
                $this->stdout("Found $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
577
            }
578
579 1
            foreach ($migrations as $migration) {
580 1
                $this->stdout("\t" . $migration . "\n");
581
            }
582
        }
583 1
    }
584
585
    /**
586
     * Creates a new migration.
587
     *
588
     * This command creates a new migration using the available migration template.
589
     * After using this command, developers should modify the created migration
590
     * skeleton by filling up the actual migration logic.
591
     *
592
     * ```
593
     * yii migrate/create create_user_table
594
     * ```
595
     *
596
     * In order to generate a namespaced migration, you should specify a namespace before the migration's name.
597
     * Note that backslash (`\`) is usually considered a special character in the shell, so you need to escape it
598
     * properly to avoid shell errors or incorrect behavior.
599
     * For example:
600
     *
601
     * ```
602
     * yii migrate/create 'app\\migrations\\createUserTable'
603
     * ```
604
     *
605
     * In case [[migrationPath]] is not set and no namespace is provided, the first entry of [[migrationNamespaces]] will be used.
606
     *
607
     * @param string $name the name of the new migration. This should only contain
608
     * letters, digits, underscores and/or backslashes.
609
     *
610
     * Note: If the migration name is of a special form, for example create_xxx or
611
     * drop_xxx, then the generated migration file will contain extra code,
612
     * in this case for creating/dropping tables.
613
     *
614
     * @throws Exception if the name argument is invalid.
615
     */
616 9
    public function actionCreate($name)
617
    {
618 9
        if (!preg_match('/^[\w\\\\]+$/', $name)) {
619
            throw new Exception('The migration name should contain letters, digits, underscore and/or backslash characters only.');
620
        }
621
622 9
        [$namespace, $className] = $this->generateClassName($name);
0 ignored issues
show
Bug introduced by
The variable $namespace does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $className does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
623 9
        $migrationPath = $this->findMigrationPath($namespace);
624
625 9
        $file = $migrationPath . DIRECTORY_SEPARATOR . $className . '.php';
626 9
        if ($this->confirm("Create new migration '$file'?")) {
627 9
            $content = $this->generateMigrationSourceCode([
628 9
                'name' => $name,
629 9
                'className' => $className,
630 9
                'namespace' => $namespace,
631
            ]);
632 9
            FileHelper::createDirectory($migrationPath);
633 9
            file_put_contents($file, $content);
634 9
            $this->stdout("New migration created successfully.\n", Console::FG_GREEN);
635
        }
636 9
    }
637
638
    /**
639
     * Generates class base name and namespace from migration name from user input.
640
     * @param string $name migration name from user input.
641
     * @return array list of 2 elements: 'namespace' and 'class base name'
642
     * @since 2.0.10
643
     */
644 9
    private function generateClassName($name)
645
    {
646 9
        $namespace = null;
647 9
        $name = trim($name, '\\');
648 9
        if (strpos($name, '\\') !== false) {
649 1
            $namespace = substr($name, 0, strrpos($name, '\\'));
650 1
            $name = substr($name, strrpos($name, '\\') + 1);
651
        } else {
652 9
            if ($this->migrationPath === null) {
653 1
                $migrationNamespaces = $this->migrationNamespaces;
654 1
                $namespace = array_shift($migrationNamespaces);
655
            }
656
        }
657
658 9
        if ($namespace === null) {
659 9
            $class = 'm' . gmdate('ymd_His') . '_' . $name;
660
        } else {
661 1
            $class = 'M' . gmdate('ymdHis') . ucfirst($name);
662
        }
663
664 9
        return [$namespace, $class];
665
    }
666
667
    /**
668
     * Finds the file path for the specified migration namespace.
669
     * @param string|null $namespace migration namespace.
670
     * @return string migration file path.
671
     * @throws Exception on failure.
672
     * @since 2.0.10
673
     */
674 9
    private function findMigrationPath($namespace)
675
    {
676 9
        if (empty($namespace)) {
677 9
            return is_array($this->migrationPath) ? reset($this->migrationPath) : $this->migrationPath;
678
        }
679
680 1
        if (!in_array($namespace, $this->migrationNamespaces, true)) {
681
            throw new Exception("Namespace '{$namespace}' not found in `migrationNamespaces`");
682
        }
683
684 1
        return $this->getNamespacePath($namespace);
685
    }
686
687
    /**
688
     * Returns the file path matching the give namespace.
689
     * @param string $namespace namespace.
690
     * @return string file path.
691
     * @since 2.0.10
692
     */
693 7
    private function getNamespacePath($namespace)
694
    {
695 7
        return str_replace('/', DIRECTORY_SEPARATOR, Yii::getAlias('@' . str_replace('\\', '/', $namespace)));
696
    }
697
698
    /**
699
     * Upgrades with the specified migration class.
700
     * @param string $class the migration class name
701
     * @return bool whether the migration is successful
702
     */
703 21
    protected function migrateUp($class)
704
    {
705 21
        if ($class === self::BASE_MIGRATION) {
706
            return true;
707
        }
708
709 21
        $this->stdout("*** applying $class\n", Console::FG_YELLOW);
710 21
        $start = microtime(true);
711 21
        $migration = $this->createMigration($class);
712 21
        if ($migration->up() !== false) {
713 21
            $this->addMigrationHistory($class);
714 21
            $time = microtime(true) - $start;
715 21
            $this->stdout("*** applied $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN);
716
717 21
            return true;
718
        }
719
720
        $time = microtime(true) - $start;
721
        $this->stdout("*** failed to apply $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED);
722
723
        return false;
724
    }
725
726
    /**
727
     * Downgrades with the specified migration class.
728
     * @param string $class the migration class name
729
     * @return bool whether the migration is successful
730
     */
731 12
    protected function migrateDown($class)
732
    {
733 12
        if ($class === self::BASE_MIGRATION) {
734
            return true;
735
        }
736
737 12
        $this->stdout("*** reverting $class\n", Console::FG_YELLOW);
738 12
        $start = microtime(true);
739 12
        $migration = $this->createMigration($class);
740 12
        if ($migration->down() !== false) {
741 12
            $this->removeMigrationHistory($class);
742 12
            $time = microtime(true) - $start;
743 12
            $this->stdout("*** reverted $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN);
744
745 12
            return true;
746
        }
747
748
        $time = microtime(true) - $start;
749
        $this->stdout("*** failed to revert $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED);
750
751
        return false;
752
    }
753
754
    /**
755
     * Creates a new migration instance.
756
     * @param string $class the migration class name
757
     * @return \yii\db\MigrationInterface the migration instance
758
     */
759
    protected function createMigration($class)
760
    {
761
        $this->includeMigrationFile($class);
762
        return new $class(['compact' => $this->compact]);
763
    }
764
765
    /**
766
     * Includes the migration file for a given migration class name.
767
     *
768
     * This function will do nothing on namespaced migrations, which are loaded by
769
     * autoloading automatically. It will include the migration file, by searching
770
     * [[migrationPath]] for classes without namespace.
771
     * @param string $class the migration class name.
772
     * @since 2.0.12
773
     */
774 21
    protected function includeMigrationFile($class)
775
    {
776 21
        $class = trim($class, '\\');
777 21
        if (strpos($class, '\\') === false) {
778 17
            if (is_array($this->migrationPath)) {
779 7
                foreach ($this->migrationPath as $path) {
780 7
                    $file = $path . DIRECTORY_SEPARATOR . $class . '.php';
781 7
                    if (is_file($file)) {
782 7
                        require_once $file;
783 7
                        break;
784
                    }
785
                }
786
            } else {
787 10
                $file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php';
788 10
                require_once $file;
789
            }
790
        }
791 21
    }
792
793
    /**
794
     * Migrates to the specified apply time in the past.
795
     * @param int $time UNIX timestamp value.
796
     */
797
    protected function migrateToTime($time)
798
    {
799
        $count = 0;
800
        $migrations = array_values($this->getMigrationHistory(null));
801
        while ($count < count($migrations) && $migrations[$count] > $time) {
802
            ++$count;
803
        }
804
        if ($count === 0) {
805
            $this->stdout("Nothing needs to be done.\n", Console::FG_GREEN);
806
        } else {
807
            $this->actionDown($count);
808
        }
809
    }
810
811
    /**
812
     * Migrates to the certain version.
813
     * @param string $version name in the full format.
814
     * @return int CLI exit code
815
     * @throws Exception if the provided version cannot be found.
816
     */
817 3
    protected function migrateToVersion($version)
818
    {
819 3
        $originalVersion = $version;
820
821
        // try migrate up
822 3
        $migrations = $this->getNewMigrations();
823 3
        foreach ($migrations as $i => $migration) {
824 2
            if (strpos($migration, $version) === 0) {
825 2
                $this->actionUp($i + 1);
826
827 2
                return ExitCode::OK;
828
            }
829
        }
830
831
        // try migrate down
832 1
        $migrations = array_keys($this->getMigrationHistory(null));
833 1
        foreach ($migrations as $i => $migration) {
834 1
            if (strpos($migration, $version) === 0) {
835 1
                if ($i === 0) {
836
                    $this->stdout("Already at '$originalVersion'. Nothing needs to be done.\n", Console::FG_YELLOW);
837
                } else {
838 1
                    $this->actionDown($i);
839
                }
840
841 1
                return ExitCode::OK;
842
            }
843
        }
844
845
        throw new Exception("Unable to find the version '$originalVersion'.");
846
    }
847
848
    /**
849
     * Returns the migrations that are not applied.
850
     * @return array list of new migrations
851
     */
852 24
    protected function getNewMigrations()
853
    {
854 24
        $applied = [];
855 24
        foreach ($this->getMigrationHistory(null) as $class => $time) {
856 3
            $applied[trim($class, '\\')] = true;
857
        }
858
859 24
        $migrationPaths = [];
860 24
        if (is_array($this->migrationPath)) {
861 7
            foreach ($this->migrationPath as $path) {
862 7
                $migrationPaths[] = [$path, ''];
863
            }
864 17
        } elseif (!empty($this->migrationPath)) {
865 12
            $migrationPaths[] = [$this->migrationPath, ''];
866
        }
867 24
        foreach ($this->migrationNamespaces as $namespace) {
868 6
            $migrationPaths[] = [$this->getNamespacePath($namespace), $namespace];
869
        }
870
871 24
        $migrations = [];
872 24
        foreach ($migrationPaths as $item) {
873 24
            list($migrationPath, $namespace) = $item;
874 24
            if (!file_exists($migrationPath)) {
875
                continue;
876
            }
877 24
            $handle = opendir($migrationPath);
878 24
            while (($file = readdir($handle)) !== false) {
879 24
                if ($file === '.' || $file === '..') {
880 24
                    continue;
881
                }
882 23
                $path = $migrationPath . DIRECTORY_SEPARATOR . $file;
883 23
                if (preg_match('/^(m(\d{6}_?\d{6})\D.*?)\.php$/is', $file, $matches) && is_file($path)) {
884 23
                    $class = $matches[1];
885 23
                    if (!empty($namespace)) {
886 6
                        $class = $namespace . '\\' . $class;
887
                    }
888 23
                    $time = str_replace('_', '', $matches[2]);
889 23
                    if (!isset($applied[$class])) {
890 23
                        $migrations[$time . '\\' . $class] = $class;
891
                    }
892
                }
893
            }
894 24
            closedir($handle);
895
        }
896 24
        ksort($migrations);
897
898 24
        return array_values($migrations);
899
    }
900
901
    /**
902
     * Generates new migration source PHP code.
903
     * Child class may override this method, adding extra logic or variation to the process.
904
     * @param array $params generation parameters, usually following parameters are present:
905
     *
906
     *  - name: string migration base name
907
     *  - className: string migration class name
908
     *
909
     * @return string generated PHP code.
910
     * @since 2.0.8
911
     */
912
    protected function generateMigrationSourceCode($params)
913
    {
914
        return $this->renderFile(Yii::getAlias($this->templateFile), $params);
0 ignored issues
show
Bug introduced by
It seems like \Yii::getAlias($this->templateFile) targeting yii\BaseYii::getAlias() can also be of type boolean; however, yii\base\Controller::renderFile() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
915
    }
916
917
    /**
918
     * Truncates the database.
919
     * This method should be overwritten in subclasses to implement the task of clearing the database.
920
     * @throws NotSupportedException if not overridden
921
     * @since 2.0.13
922
     */
923
    protected function truncateDatabase()
924
    {
925
        throw new NotSupportedException('This command is not implemented in ' . get_class($this));
926
    }
927
928
    /**
929
     * Returns the migration history.
930
     * @param int $limit the maximum number of records in the history to be returned. `null` for "no limit".
931
     * @return array the migration history
932
     */
933
    abstract protected function getMigrationHistory($limit);
934
935
    /**
936
     * Adds new migration entry to the history.
937
     * @param string $version migration version name.
938
     */
939
    abstract protected function addMigrationHistory($version);
940
941
    /**
942
     * Removes existing migration from the history.
943
     * @param string $version migration version name.
944
     */
945
    abstract protected function removeMigrationHistory($version);
946
}
947