Completed
Push — master ( 2faf77...993eb5 )
by Dmitry
11:18
created

BaseMigrateController::removeMigrationHistory()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
c 0
b 0
f 0
ccs 0
cts 0
cp 0
nc 1
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\BaseObject;
12
use yii\base\InvalidConfigException;
13
use yii\base\NotSupportedException;
14
use yii\console\Controller;
15
use yii\console\Exception;
16
use yii\console\ExitCode;
17
use yii\db\MigrationInterface;
18
use yii\helpers\Console;
19
use yii\helpers\FileHelper;
20
21
/**
22
 * BaseMigrateController is the base class for migrate controllers.
23
 *
24
 * @author Qiang Xue <[email protected]>
25
 * @since 2.0
26
 */
27
abstract class BaseMigrateController extends Controller
28
{
29
    /**
30
     * The name of the dummy migration that marks the beginning of the whole migration history.
31
     */
32
    const BASE_MIGRATION = 'm000000_000000_base';
33
34
35
    /**
36
     * @var string the default command action.
37
     */
38
    public $defaultAction = 'up';
39
    /**
40
     * @var string|array the directory containing the migration classes. This can be either
41
     * a [path alias](guide:concept-aliases) or a directory path.
42
     *
43
     * Migration classes located at this path should be declared without a namespace.
44
     * Use [[migrationNamespaces]] property in case you are using namespaced migrations.
45
     *
46
     * If you have set up [[migrationNamespaces]], you may set this field to `null` in order
47
     * to disable usage of migrations that are not namespaced.
48
     *
49
     * Since version 2.0.12 you may also specify an array of migration paths that should be searched for
50
     * migrations to load. This is mainly useful to support old extensions that provide migrations
51
     * without namespace and to adopt the new feature of namespaced migrations while keeping existing migrations.
52
     *
53
     * In general, to load migrations from different locations, [[migrationNamespaces]] is the preferable solution
54
     * as the migration name contains the origin of the migration in the history, which is not the case when
55
     * using multiple migration paths.
56
     *
57
     * @see $migrationNamespaces
58
     */
59
    public $migrationPath = ['@app/migrations'];
60
    /**
61
     * @var array list of namespaces containing the migration classes.
62
     *
63
     * Migration namespaces should be resolvable as a [path alias](guide:concept-aliases) if prefixed with `@`, e.g. if you specify
64
     * the namespace `app\migrations`, the code `Yii::getAlias('@app/migrations')` should be able to return
65
     * the file path to the directory this namespace refers to.
66
     * This corresponds with the [autoloading conventions](guide:concept-autoloading) of Yii.
67
     *
68
     * For example:
69
     *
70
     * ```php
71
     * [
72
     *     'app\migrations',
73
     *     'some\extension\migrations',
74
     * ]
75
     * ```
76
     *
77
     * @since 2.0.10
78
     * @see $migrationPath
79
     */
80
    public $migrationNamespaces = [];
81
    /**
82
     * @var string the template file for generating new migrations.
83
     * This can be either a [path alias](guide:concept-aliases) (e.g. "@app/migrations/template.php")
84
     * or a file path.
85
     */
86
    public $templateFile;
87
88
    /**
89
     * @var bool indicates whether the console output should be compacted.
90
     * If this is set to true, the individual commands ran within the migration will not be output to the console.
91
     * Default is false, in other words the output is fully verbose by default.
92
     * @since 2.0.13
93
     */
94
    public $compact = false;
95
96
    /**
97
     * @inheritdoc
98
     */
99 40
    public function options($actionID)
100
    {
101 40
        return array_merge(
102 40
            parent::options($actionID),
103 40
            ['migrationPath', 'migrationNamespaces', 'compact'], // global for all actions
104 40
            $actionID === 'create' ? ['templateFile'] : [] // action create
105
        );
106
    }
107
108
    /**
109
     * This method is invoked right before an action is to be executed (after all possible filters.)
110
     * It checks the existence of the [[migrationPath]].
111
     * @param \yii\base\Action $action the action to be executed.
112
     * @throws InvalidConfigException if directory specified in migrationPath doesn't exist and action isn't "create".
113
     * @return bool whether the action should continue to be executed.
114
     */
115 50
    public function beforeAction($action)
116
    {
117 50
        if (parent::beforeAction($action)) {
118 50
            if (empty($this->migrationNamespaces) && empty($this->migrationPath)) {
119
                throw new InvalidConfigException('At least one of `migrationPath` or `migrationNamespaces` should be specified.');
120
            }
121
122 50
            foreach ($this->migrationNamespaces as $key => $value) {
123 8
                $this->migrationNamespaces[$key] = trim($value, '\\');
124
            }
125
126 50
            if (is_array($this->migrationPath)) {
127 7
                foreach ($this->migrationPath as $i => $path) {
128 7
                    $this->migrationPath[$i] = Yii::getAlias($path);
129
                }
130 43
            } elseif ($this->migrationPath !== null) {
131 37
                $path = Yii::getAlias($this->migrationPath);
132 37
                if (!is_dir($path)) {
133 5
                    if ($action->id !== 'create') {
134
                        throw new InvalidConfigException("Migration failed. Directory specified in migrationPath doesn't exist: {$this->migrationPath}");
135
                    }
136 5
                    FileHelper::createDirectory($path);
0 ignored issues
show
Bug introduced by
It seems like $path defined by \Yii::getAlias($this->migrationPath) on line 131 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...
137
                }
138 37
                $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...
139
            }
140
141 50
            $version = Yii::getVersion();
142 50
            $this->stdout("Yii Migration Tool (based on Yii v{$version})\n\n");
143
144 50
            return true;
145
        }
146
147
        return false;
148
    }
149
150
    /**
151
     * Upgrades the application by applying new migrations.
152
     *
153
     * For example,
154
     *
155
     * ```
156
     * yii migrate     # apply all new migrations
157
     * yii migrate 3   # apply the first 3 new migrations
158
     * ```
159
     *
160
     * @param int $limit the number of new migrations to be applied. If 0, it means
161
     * applying all available new migrations.
162
     *
163
     * @return int the status of the action execution. 0 means normal, other values mean abnormal.
164
     */
165 38
    public function actionUp($limit = 0)
166
    {
167 38
        $migrations = $this->getNewMigrations();
168 38
        if (empty($migrations)) {
169 1
            $this->stdout("No new migrations found. Your system is up-to-date.\n", Console::FG_GREEN);
170
171 1
            return ExitCode::OK;
172
        }
173
174 37
        $total = count($migrations);
175 37
        $limit = (int) $limit;
176 37
        if ($limit > 0) {
177 4
            $migrations = array_slice($migrations, 0, $limit);
178
        }
179
180 37
        $n = count($migrations);
181 37
        if ($n === $total) {
182 36
            $this->stdout("Total $n new " . ($n === 1 ? 'migration' : 'migrations') . " to be applied:\n", Console::FG_YELLOW);
183
        } else {
184 2
            $this->stdout("Total $n out of $total new " . ($total === 1 ? 'migration' : 'migrations') . " to be applied:\n", Console::FG_YELLOW);
185
        }
186
187 37
        foreach ($migrations as $migration) {
188 37
            $nameLimit = $this->getMigrationNameLimit();
189 37
            if ($nameLimit !== null && strlen($migration) > $nameLimit) {
190 1
                $this->stdout("\nThe migration name '$migration' is too long. Its not possible to apply this migration.\n", Console::FG_RED);
191 1
                return ExitCode::UNSPECIFIED_ERROR;
192
            }
193 36
            $this->stdout("\t$migration\n");
194
        }
195 36
        $this->stdout("\n");
196
197 36
        $applied = 0;
198 36
        if ($this->confirm('Apply the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) {
199 36
            foreach ($migrations as $migration) {
200 36
                if (!$this->migrateUp($migration)) {
201
                    $this->stdout("\n$applied from $n " . ($applied === 1 ? 'migration was' : 'migrations were') . " applied.\n", Console::FG_RED);
202
                    $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
203
204
                    return ExitCode::UNSPECIFIED_ERROR;
205
                }
206 36
                $applied++;
207
            }
208
209 36
            $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " applied.\n", Console::FG_GREEN);
210 36
            $this->stdout("\nMigrated up successfully.\n", Console::FG_GREEN);
211
        }
212 36
    }
213
214
    /**
215
     * Downgrades the application by reverting old migrations.
216
     *
217
     * For example,
218
     *
219
     * ```
220
     * yii migrate/down     # revert the last migration
221
     * yii migrate/down 3   # revert the last 3 migrations
222
     * yii migrate/down all # revert all migrations
223
     * ```
224
     *
225
     * @param int|string $limit the number of migrations to be reverted. Defaults to 1,
226
     * meaning the last applied migration will be reverted. When value is "all", all migrations will be reverted.
227
     * @throws Exception if the number of the steps specified is less than 1.
228
     *
229
     * @return int the status of the action execution. 0 means normal, other values mean abnormal.
230
     */
231 25
    public function actionDown($limit = 1)
232
    {
233 25
        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...
234 16
            $limit = null;
235
        } else {
236 12
            $limit = (int) $limit;
237 12
            if ($limit < 1) {
238
                throw new Exception('The step argument must be greater than 0.');
239
            }
240
        }
241
242 25
        $migrations = $this->getMigrationHistory($limit);
243
244 25
        if (empty($migrations)) {
245 15
            $this->stdout("No migration has been done before.\n", Console::FG_YELLOW);
246
247 15
            return ExitCode::OK;
248
        }
249
250 25
        $migrations = array_keys($migrations);
251
252 25
        $n = count($migrations);
253 25
        $this->stdout("Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be reverted:\n", Console::FG_YELLOW);
254 25
        foreach ($migrations as $migration) {
255 25
            $this->stdout("\t$migration\n");
256
        }
257 25
        $this->stdout("\n");
258
259 25
        $reverted = 0;
260 25
        if ($this->confirm('Revert the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) {
261 25
            foreach ($migrations as $migration) {
262 25
                if (!$this->migrateDown($migration)) {
263
                    $this->stdout("\n$reverted from $n " . ($reverted === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_RED);
264
                    $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
265
266
                    return ExitCode::UNSPECIFIED_ERROR;
267
                }
268 25
                $reverted++;
269
            }
270 25
            $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_GREEN);
271 25
            $this->stdout("\nMigrated down successfully.\n", Console::FG_GREEN);
272
        }
273 25
    }
274
275
    /**
276
     * Redoes the last few migrations.
277
     *
278
     * This command will first revert the specified migrations, and then apply
279
     * them again. For example,
280
     *
281
     * ```
282
     * yii migrate/redo     # redo the last applied migration
283
     * yii migrate/redo 3   # redo the last 3 applied migrations
284
     * yii migrate/redo all # redo all migrations
285
     * ```
286
     *
287
     * @param int|string $limit the number of migrations to be redone. Defaults to 1,
288
     * meaning the last applied migration will be redone. When equals "all", all migrations will be redone.
289
     * @throws Exception if the number of the steps specified is less than 1.
290
     *
291
     * @return int the status of the action execution. 0 means normal, other values mean abnormal.
292
     */
293 2
    public function actionRedo($limit = 1)
294
    {
295 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...
296
            $limit = null;
297
        } else {
298 2
            $limit = (int) $limit;
299 2
            if ($limit < 1) {
300
                throw new Exception('The step argument must be greater than 0.');
301
            }
302
        }
303
304 2
        $migrations = $this->getMigrationHistory($limit);
305
306 2
        if (empty($migrations)) {
307
            $this->stdout("No migration has been done before.\n", Console::FG_YELLOW);
308
309
            return ExitCode::OK;
310
        }
311
312 2
        $migrations = array_keys($migrations);
313
314 2
        $n = count($migrations);
315 2
        $this->stdout("Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be redone:\n", Console::FG_YELLOW);
316 2
        foreach ($migrations as $migration) {
317 2
            $this->stdout("\t$migration\n");
318
        }
319 2
        $this->stdout("\n");
320
321 2
        if ($this->confirm('Redo the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) {
322 2
            foreach ($migrations as $migration) {
323 2
                if (!$this->migrateDown($migration)) {
324
                    $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
325
326 2
                    return ExitCode::UNSPECIFIED_ERROR;
327
                }
328
            }
329 2
            foreach (array_reverse($migrations) as $migration) {
330 2
                if (!$this->migrateUp($migration)) {
331
                    $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
332
333 2
                    return ExitCode::UNSPECIFIED_ERROR;
334
                }
335
            }
336 2
            $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " redone.\n", Console::FG_GREEN);
337 2
            $this->stdout("\nMigration redone successfully.\n", Console::FG_GREEN);
338
        }
339 2
    }
340
341
    /**
342
     * Upgrades or downgrades till the specified version.
343
     *
344
     * Can also downgrade versions to the certain apply time in the past by providing
345
     * a UNIX timestamp or a string parseable by the strtotime() function. This means
346
     * that all the versions applied after the specified certain time would be reverted.
347
     *
348
     * This command will first revert the specified migrations, and then apply
349
     * them again. For example,
350
     *
351
     * ```
352
     * yii migrate/to 101129_185401                          # using timestamp
353
     * yii migrate/to m101129_185401_create_user_table       # using full name
354
     * yii migrate/to 1392853618                             # using UNIX timestamp
355
     * yii migrate/to "2014-02-15 13:00:50"                  # using strtotime() parseable string
356
     * yii migrate/to app\migrations\M101129185401CreateUser # using full namespace name
357
     * ```
358
     *
359
     * @param string $version either the version name or the certain time value in the past
360
     * that the application should be migrated to. This can be either the timestamp,
361
     * the full name of the migration, the UNIX timestamp, or the parseable datetime
362
     * string.
363
     * @throws Exception if the version argument is invalid.
364
     */
365 3
    public function actionTo($version)
366
    {
367 3
        if (($namespaceVersion = $this->extractNamespaceMigrationVersion($version)) !== false) {
368 1
            $this->migrateToVersion($namespaceVersion);
369 2
        } elseif (($migrationName = $this->extractMigrationVersion($version)) !== false) {
370 2
            $this->migrateToVersion($migrationName);
371
        } elseif ((string) (int) $version == $version) {
372
            $this->migrateToTime($version);
373
        } elseif (($time = strtotime($version)) !== false) {
374
            $this->migrateToTime($time);
375
        } else {
376
            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).");
377
        }
378 3
    }
379
380
    /**
381
     * Modifies the migration history to the specified version.
382
     *
383
     * No actual migration will be performed.
384
     *
385
     * ```
386
     * yii migrate/mark 101129_185401                        # using timestamp
387
     * yii migrate/mark m101129_185401_create_user_table     # using full name
388
     * yii migrate/mark app\migrations\M101129185401CreateUser # using full namespace name
389
     * yii migrate/mark m000000_000000_base # reset the complete migration history
390
     * ```
391
     *
392
     * @param string $version the version at which the migration history should be marked.
393
     * This can be either the timestamp or the full name of the migration.
394
     * You may specify the name `m000000_000000_base` to set the migration history to a
395
     * state where no migration has been applied.
396
     * @return int CLI exit code
397
     * @throws Exception if the version argument is invalid or the version cannot be found.
398
     */
399 4
    public function actionMark($version)
400
    {
401 4
        $originalVersion = $version;
402 4
        if (($namespaceVersion = $this->extractNamespaceMigrationVersion($version)) !== false) {
403 1
            $version = $namespaceVersion;
404 3
        } elseif (($migrationName = $this->extractMigrationVersion($version)) !== false) {
405 3
            $version = $migrationName;
406
        } elseif ($version !== static::BASE_MIGRATION) {
407
            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).");
408
        }
409
410
        // try mark up
411 4
        $migrations = $this->getNewMigrations();
412 4
        foreach ($migrations as $i => $migration) {
413 3
            if (strpos($migration, $version) === 0) {
414 3
                if ($this->confirm("Set migration history at $originalVersion?")) {
415 3
                    for ($j = 0; $j <= $i; ++$j) {
416 3
                        $this->addMigrationHistory($migrations[$j]);
417
                    }
418 3
                    $this->stdout("The migration history is set at $originalVersion.\nNo actual migration was performed.\n", Console::FG_GREEN);
419
                }
420
421 3
                return ExitCode::OK;
422
            }
423
        }
424
425
        // try mark down
426 1
        $migrations = array_keys($this->getMigrationHistory(null));
427 1
        $migrations[] = static::BASE_MIGRATION;
428 1
        foreach ($migrations as $i => $migration) {
429 1
            if (strpos($migration, $version) === 0) {
430 1
                if ($i === 0) {
431
                    $this->stdout("Already at '$originalVersion'. Nothing needs to be done.\n", Console::FG_YELLOW);
432
                } else {
433 1
                    if ($this->confirm("Set migration history at $originalVersion?")) {
434 1
                        for ($j = 0; $j < $i; ++$j) {
435 1
                            $this->removeMigrationHistory($migrations[$j]);
436
                        }
437 1
                        $this->stdout("The migration history is set at $originalVersion.\nNo actual migration was performed.\n", Console::FG_GREEN);
438
                    }
439
                }
440
441 1
                return ExitCode::OK;
442
            }
443
        }
444
445
        throw new Exception("Unable to find the version '$originalVersion'.");
446
    }
447
448
    /**
449
     * Truncates the whole database and starts the migration from the beginning.
450
     *
451
     * ```
452
     * yii migrate/fresh
453
     * ```
454
     *
455
     * @since 2.0.13
456
     */
457 1
    public function actionFresh()
458
    {
459 1
        if (YII_ENV_PROD) {
460
            $this->stdout("YII_ENV is set to 'prod'.\nRefreshing migrations is not possible on production systems.\n");
461
            return ExitCode::OK;
462
        }
463
464 1
        if ($this->confirm(
465 1
            "Are you sure you want to reset the database and start the migration from the beginning?\nAll data will be lost irreversibly!")) {
466 1
            $this->truncateDatabase();
467 1
            $this->actionUp();
468
        } else {
469
            $this->stdout('Action was cancelled by user. Nothing has been performed.');
470
        }
471 1
    }
472
473
    /**
474
     * Checks if given migration version specification matches namespaced migration name.
475
     * @param string $rawVersion raw version specification received from user input.
476
     * @return string|false actual migration version, `false` - if not match.
477
     * @since 2.0.10
478
     */
479 6
    private function extractNamespaceMigrationVersion($rawVersion)
480
    {
481 6
        if (preg_match('/^\\\\?([\w_]+\\\\)+m(\d{6}_?\d{6})(\D.*)?$/is', $rawVersion, $matches)) {
482 2
            return trim($rawVersion, '\\');
483
        }
484
485 4
        return false;
486
    }
487
488
    /**
489
     * Checks if given migration version specification matches migration base name.
490
     * @param string $rawVersion raw version specification received from user input.
491
     * @return string|false actual migration version, `false` - if not match.
492
     * @since 2.0.10
493
     */
494 4
    private function extractMigrationVersion($rawVersion)
495
    {
496 4
        if (preg_match('/^m?(\d{6}_?\d{6})(\D.*)?$/is', $rawVersion, $matches)) {
497 4
            return 'm' . $matches[1];
498
        }
499
500
        return false;
501
    }
502
503
    /**
504
     * Displays the migration history.
505
     *
506
     * This command will show the list of migrations that have been applied
507
     * so far. For example,
508
     *
509
     * ```
510
     * yii migrate/history     # showing the last 10 migrations
511
     * yii migrate/history 5   # showing the last 5 migrations
512
     * yii migrate/history all # showing the whole history
513
     * ```
514
     *
515
     * @param int|string $limit the maximum number of migrations to be displayed.
516
     * If it is "all", the whole migration history will be displayed.
517
     * @throws \yii\console\Exception if invalid limit value passed
518
     */
519 6
    public function actionHistory($limit = 10)
520
    {
521 6
        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...
522
            $limit = null;
523
        } else {
524 6
            $limit = (int) $limit;
525 6
            if ($limit < 1) {
526
                throw new Exception('The limit must be greater than 0.');
527
            }
528
        }
529
530 6
        $migrations = $this->getMigrationHistory($limit);
531
532 6
        if (empty($migrations)) {
533 6
            $this->stdout("No migration has been done before.\n", Console::FG_YELLOW);
534
        } else {
535 2
            $n = count($migrations);
536 2
            if ($limit > 0) {
537 2
                $this->stdout("Showing the last $n applied " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
538
            } else {
539
                $this->stdout("Total $n " . ($n === 1 ? 'migration has' : 'migrations have') . " been applied before:\n", Console::FG_YELLOW);
540
            }
541 2
            foreach ($migrations as $version => $time) {
542 2
                $this->stdout("\t(" . date('Y-m-d H:i:s', $time) . ') ' . $version . "\n");
543
            }
544
        }
545 6
    }
546
547
    /**
548
     * Displays the un-applied new migrations.
549
     *
550
     * This command will show the new migrations that have not been applied.
551
     * For example,
552
     *
553
     * ```
554
     * yii migrate/new     # showing the first 10 new migrations
555
     * yii migrate/new 5   # showing the first 5 new migrations
556
     * yii migrate/new all # showing all new migrations
557
     * ```
558
     *
559
     * @param int|string $limit the maximum number of new migrations to be displayed.
560
     * If it is `all`, all available new migrations will be displayed.
561
     * @throws \yii\console\Exception if invalid limit value passed
562
     */
563 1
    public function actionNew($limit = 10)
564
    {
565 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...
566
            $limit = null;
567
        } else {
568 1
            $limit = (int) $limit;
569 1
            if ($limit < 1) {
570
                throw new Exception('The limit must be greater than 0.');
571
            }
572
        }
573
574 1
        $migrations = $this->getNewMigrations();
575
576 1
        if (empty($migrations)) {
577 1
            $this->stdout("No new migrations found. Your system is up-to-date.\n", Console::FG_GREEN);
578
        } else {
579 1
            $n = count($migrations);
580 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...
581
                $migrations = array_slice($migrations, 0, $limit);
582
                $this->stdout("Showing $limit out of $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
583
            } else {
584 1
                $this->stdout("Found $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
585
            }
586
587 1
            foreach ($migrations as $migration) {
588 1
                $this->stdout("\t" . $migration . "\n");
589
            }
590
        }
591 1
    }
592
593
    /**
594
     * Creates a new migration.
595
     *
596
     * This command creates a new migration using the available migration template.
597
     * After using this command, developers should modify the created migration
598
     * skeleton by filling up the actual migration logic.
599
     *
600
     * ```
601
     * yii migrate/create create_user_table
602
     * ```
603
     *
604
     * In order to generate a namespaced migration, you should specify a namespace before the migration's name.
605
     * Note that backslash (`\`) is usually considered a special character in the shell, so you need to escape it
606
     * properly to avoid shell errors or incorrect behavior.
607
     * For example:
608
     *
609
     * ```
610
     * yii migrate/create 'app\\migrations\\createUserTable'
611
     * ```
612
     *
613
     * In case [[migrationPath]] is not set and no namespace is provided, the first entry of [[migrationNamespaces]] will be used.
614
     *
615
     * @param string $name the name of the new migration. This should only contain
616
     * letters, digits, underscores and/or backslashes.
617
     *
618
     * Note: If the migration name is of a special form, for example create_xxx or
619
     * drop_xxx, then the generated migration file will contain extra code,
620
     * in this case for creating/dropping tables.
621
     *
622
     * @throws Exception if the name argument is invalid.
623
     */
624 10
    public function actionCreate($name)
625
    {
626 10
        if (!preg_match('/^[\w\\\\]+$/', $name)) {
627
            throw new Exception('The migration name should contain letters, digits, underscore and/or backslash characters only.');
628
        }
629
630 10
        list($namespace, $className) = $this->generateClassName($name);
631
        // Abort if name is too long
632 10
        $nameLimit = $this->getMigrationNameLimit();
633 10
        if ($nameLimit !== null && strlen($className) > $nameLimit) {
634 1
            throw new Exception('The migration name is too long.');
635
        }
636
637 9
        $migrationPath = $this->findMigrationPath($namespace);
638
639 9
        $file = $migrationPath . DIRECTORY_SEPARATOR . $className . '.php';
640 9
        if ($this->confirm("Create new migration '$file'?")) {
641 9
            $content = $this->generateMigrationSourceCode([
642 9
                'name' => $name,
643 9
                'className' => $className,
644 9
                'namespace' => $namespace,
645
            ]);
646 9
            FileHelper::createDirectory($migrationPath);
647 9
            file_put_contents($file, $content);
648 9
            $this->stdout("New migration created successfully.\n", Console::FG_GREEN);
649
        }
650 9
    }
651
652
    /**
653
     * Generates class base name and namespace from migration name from user input.
654
     * @param string $name migration name from user input.
655
     * @return array list of 2 elements: 'namespace' and 'class base name'
656
     * @since 2.0.10
657
     */
658 10
    private function generateClassName($name)
659
    {
660 10
        $namespace = null;
661 10
        $name = trim($name, '\\');
662 10
        if (strpos($name, '\\') !== false) {
663 1
            $namespace = substr($name, 0, strrpos($name, '\\'));
664 1
            $name = substr($name, strrpos($name, '\\') + 1);
665
        } else {
666 10
            if ($this->migrationPath === null) {
667 1
                $migrationNamespaces = $this->migrationNamespaces;
668 1
                $namespace = array_shift($migrationNamespaces);
669
            }
670
        }
671
672 10
        if ($namespace === null) {
673 10
            $class = 'm' . gmdate('ymd_His') . '_' . $name;
674
        } else {
675 1
            $class = 'M' . gmdate('ymdHis') . ucfirst($name);
676
        }
677
678 10
        return [$namespace, $class];
679
    }
680
681
    /**
682
     * Finds the file path for the specified migration namespace.
683
     * @param string|null $namespace migration namespace.
684
     * @return string migration file path.
685
     * @throws Exception on failure.
686
     * @since 2.0.10
687
     */
688 9
    private function findMigrationPath($namespace)
689
    {
690 9
        if (empty($namespace)) {
691 9
            return is_array($this->migrationPath) ? reset($this->migrationPath) : $this->migrationPath;
692
        }
693
694 1
        if (!in_array($namespace, $this->migrationNamespaces, true)) {
695
            throw new Exception("Namespace '{$namespace}' not found in `migrationNamespaces`");
696
        }
697
698 1
        return $this->getNamespacePath($namespace);
699
    }
700
701
    /**
702
     * Returns the file path matching the give namespace.
703
     * @param string $namespace namespace.
704
     * @return string file path.
705
     * @since 2.0.10
706
     */
707 7
    private function getNamespacePath($namespace)
708
    {
709 7
        return str_replace('/', DIRECTORY_SEPARATOR, Yii::getAlias('@' . str_replace('\\', '/', $namespace)));
710
    }
711
712
    /**
713
     * Upgrades with the specified migration class.
714
     * @param string $class the migration class name
715
     * @return bool whether the migration is successful
716
     */
717 36
    protected function migrateUp($class)
718
    {
719 36
        if ($class === self::BASE_MIGRATION) {
720
            return true;
721
        }
722
723 36
        $this->stdout("*** applying $class\n", Console::FG_YELLOW);
724 36
        $start = microtime(true);
725 36
        $migration = $this->createMigration($class);
726 36
        if ($migration->up() !== false) {
727 36
            $this->addMigrationHistory($class);
728 36
            $time = microtime(true) - $start;
729 36
            $this->stdout("*** applied $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN);
730
731 36
            return true;
732
        }
733
734
        $time = microtime(true) - $start;
735
        $this->stdout("*** failed to apply $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED);
736
737
        return false;
738
    }
739
740
    /**
741
     * Downgrades with the specified migration class.
742
     * @param string $class the migration class name
743
     * @return bool whether the migration is successful
744
     */
745 26
    protected function migrateDown($class)
746
    {
747 26
        if ($class === self::BASE_MIGRATION) {
748
            return true;
749
        }
750
751 26
        $this->stdout("*** reverting $class\n", Console::FG_YELLOW);
752 26
        $start = microtime(true);
753 26
        $migration = $this->createMigration($class);
754 26
        if ($migration->down() !== false) {
755 26
            $this->removeMigrationHistory($class);
756 26
            $time = microtime(true) - $start;
757 26
            $this->stdout("*** reverted $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN);
758
759 26
            return true;
760
        }
761
762
        $time = microtime(true) - $start;
763
        $this->stdout("*** failed to revert $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED);
764
765
        return false;
766
    }
767
768
    /**
769
     * Creates a new migration instance.
770
     * @param string $class the migration class name
771
     * @return \yii\db\MigrationInterface the migration instance
772
     */
773
    protected function createMigration($class)
774
    {
775
        $this->includeMigrationFile($class);
776
777
        /** @var MigrationInterface $migration */
778
        $migration = Yii::createObject($class);
779
        if ($migration instanceof BaseObject && $migration->canSetProperty('compact')) {
780
            $migration->compact = $this->compact;
781
        }
782
783
        return $migration;
784
    }
785
786
    /**
787
     * Includes the migration file for a given migration class name.
788
     *
789
     * This function will do nothing on namespaced migrations, which are loaded by
790
     * autoloading automatically. It will include the migration file, by searching
791
     * [[migrationPath]] for classes without namespace.
792
     * @param string $class the migration class name.
793
     * @since 2.0.12
794
     */
795 36
    protected function includeMigrationFile($class)
796
    {
797 36
        $class = trim($class, '\\');
798 36
        if (strpos($class, '\\') === false) {
799 32
            if (is_array($this->migrationPath)) {
800 7
                foreach ($this->migrationPath as $path) {
801 7
                    $file = $path . DIRECTORY_SEPARATOR . $class . '.php';
802 7
                    if (is_file($file)) {
803 7
                        require_once $file;
804 7
                        break;
805
                    }
806
                }
807
            } else {
808 25
                $file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php';
809 25
                require_once $file;
810
            }
811
        }
812 36
    }
813
814
    /**
815
     * Migrates to the specified apply time in the past.
816
     * @param int $time UNIX timestamp value.
817
     */
818
    protected function migrateToTime($time)
819
    {
820
        $count = 0;
821
        $migrations = array_values($this->getMigrationHistory(null));
822
        while ($count < count($migrations) && $migrations[$count] > $time) {
823
            ++$count;
824
        }
825
        if ($count === 0) {
826
            $this->stdout("Nothing needs to be done.\n", Console::FG_GREEN);
827
        } else {
828
            $this->actionDown($count);
829
        }
830
    }
831
832
    /**
833
     * Migrates to the certain version.
834
     * @param string $version name in the full format.
835
     * @return int CLI exit code
836
     * @throws Exception if the provided version cannot be found.
837
     */
838 3
    protected function migrateToVersion($version)
839
    {
840 3
        $originalVersion = $version;
841
842
        // try migrate up
843 3
        $migrations = $this->getNewMigrations();
844 3
        foreach ($migrations as $i => $migration) {
845 2
            if (strpos($migration, $version) === 0) {
846 2
                $this->actionUp($i + 1);
847
848 2
                return ExitCode::OK;
849
            }
850
        }
851
852
        // try migrate down
853 1
        $migrations = array_keys($this->getMigrationHistory(null));
854 1
        foreach ($migrations as $i => $migration) {
855 1
            if (strpos($migration, $version) === 0) {
856 1
                if ($i === 0) {
857
                    $this->stdout("Already at '$originalVersion'. Nothing needs to be done.\n", Console::FG_YELLOW);
858
                } else {
859 1
                    $this->actionDown($i);
860
                }
861
862 1
                return ExitCode::OK;
863
            }
864
        }
865
866
        throw new Exception("Unable to find the version '$originalVersion'.");
867
    }
868
869
    /**
870
     * Returns the migrations that are not applied.
871
     * @return array list of new migrations
872
     */
873 40
    protected function getNewMigrations()
874
    {
875 40
        $applied = [];
876 40
        foreach ($this->getMigrationHistory(null) as $class => $time) {
877 3
            $applied[trim($class, '\\')] = true;
878
        }
879
880 40
        $migrationPaths = [];
881 40
        if (is_array($this->migrationPath)) {
882 7
            foreach ($this->migrationPath as $path) {
883 7
                $migrationPaths[] = [$path, ''];
884
            }
885 33
        } elseif (!empty($this->migrationPath)) {
886 28
            $migrationPaths[] = [$this->migrationPath, ''];
887
        }
888 40
        foreach ($this->migrationNamespaces as $namespace) {
889 6
            $migrationPaths[] = [$this->getNamespacePath($namespace), $namespace];
890
        }
891
892 40
        $migrations = [];
893 40
        foreach ($migrationPaths as $item) {
894 40
            list($migrationPath, $namespace) = $item;
895 40
            if (!file_exists($migrationPath)) {
896
                continue;
897
            }
898 40
            $handle = opendir($migrationPath);
899 40
            while (($file = readdir($handle)) !== false) {
900 40
                if ($file === '.' || $file === '..') {
901 40
                    continue;
902
                }
903 39
                $path = $migrationPath . DIRECTORY_SEPARATOR . $file;
904 39
                if (preg_match('/^(m(\d{6}_?\d{6})\D.*?)\.php$/is', $file, $matches) && is_file($path)) {
905 39
                    $class = $matches[1];
906 39
                    if (!empty($namespace)) {
907 6
                        $class = $namespace . '\\' . $class;
908
                    }
909 39
                    $time = str_replace('_', '', $matches[2]);
910 39
                    if (!isset($applied[$class])) {
911 39
                        $migrations[$time . '\\' . $class] = $class;
912
                    }
913
                }
914
            }
915 40
            closedir($handle);
916
        }
917 40
        ksort($migrations);
918
919 40
        return array_values($migrations);
920
    }
921
922
    /**
923
     * Generates new migration source PHP code.
924
     * Child class may override this method, adding extra logic or variation to the process.
925
     * @param array $params generation parameters, usually following parameters are present:
926
     *
927
     *  - name: string migration base name
928
     *  - className: string migration class name
929
     *
930
     * @return string generated PHP code.
931
     * @since 2.0.8
932
     */
933
    protected function generateMigrationSourceCode($params)
934
    {
935
        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...
936
    }
937
938
    /**
939
     * Truncates the database.
940
     * This method should be overwritten in subclasses to implement the task of clearing the database.
941
     * @throws NotSupportedException if not overridden
942
     * @since 2.0.13
943
     */
944
    protected function truncateDatabase()
945
    {
946
        throw new NotSupportedException('This command is not implemented in ' . get_class($this));
947
    }
948
949
    /**
950
     * Return the maximum name length for a migration.
951
     *
952
     * Subclasses may override this method to define a limit.
953
     * @return int|null the maximum name length for a migration or `null` if no limit applies.
954
     * @since 2.0.13
955
     */
956
    protected function getMigrationNameLimit()
957
    {
958
        return null;
959
    }
960
961
    /**
962
     * Returns the migration history.
963
     * @param int $limit the maximum number of records in the history to be returned. `null` for "no limit".
964
     * @return array the migration history
965
     */
966
    abstract protected function getMigrationHistory($limit);
967
968
    /**
969
     * Adds new migration entry to the history.
970
     * @param string $version migration version name.
971
     */
972
    abstract protected function addMigrationHistory($version);
973
974
    /**
975
     * Removes existing migration from the history.
976
     * @param string $version migration version name.
977
     */
978
    abstract protected function removeMigrationHistory($version);
979
}
980