Completed
Push — fix-error-handling-regression ( ef2bf2 )
by Alexander
09:24
created

MigrateController::beforeAction()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 5
cts 6
cp 0.8333
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 1
crap 3.0416
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\db\Connection;
12
use yii\db\Query;
13
use yii\di\Instance;
14
use yii\helpers\ArrayHelper;
15
use yii\helpers\Console;
16
17
/**
18
 * Manages application migrations.
19
 *
20
 * A migration means a set of persistent changes to the application environment
21
 * that is shared among different developers. For example, in an application
22
 * backed by a database, a migration may refer to a set of changes to
23
 * the database, such as creating a new table, adding a new table column.
24
 *
25
 * This command provides support for tracking the migration history, upgrading
26
 * or downloading with migrations, and creating new migration skeletons.
27
 *
28
 * The migration history is stored in a database table named
29
 * as [[migrationTable]]. The table will be automatically created the first time
30
 * this command is executed, if it does not exist. You may also manually
31
 * create it as follows:
32
 *
33
 * ```sql
34
 * CREATE TABLE migration (
35
 *     version varchar(180) PRIMARY KEY,
36
 *     apply_time integer
37
 * )
38
 * ```
39
 *
40
 * Below are some common usages of this command:
41
 *
42
 * ```
43
 * # creates a new migration named 'create_user_table'
44
 * yii migrate/create create_user_table
45
 *
46
 * # applies ALL new migrations
47
 * yii migrate
48
 *
49
 * # reverts the last applied migration
50
 * yii migrate/down
51
 * ```
52
 *
53
 * Since 2.0.10 you can use namespaced migrations. In order to enable this feature you should configure [[migrationNamespaces]]
54
 * property for the controller at application configuration:
55
 *
56
 * ```php
57
 * return [
58
 *     'controllerMap' => [
59
 *         'migrate' => [
60
 *             'class' => 'yii\console\controllers\MigrateController',
61
 *             'migrationNamespaces' => [
62
 *                 'app\migrations',
63
 *                 'some\extension\migrations',
64
 *             ],
65
 *             //'migrationPath' => null, // allows to disable not namespaced migration completely
66
 *         ],
67
 *     ],
68
 * ];
69
 * ```
70
 *
71
 * @author Qiang Xue <[email protected]>
72
 * @since 2.0
73
 */
74
class MigrateController extends BaseMigrateController
75
{
76
    /**
77
     * @var string the name of the table for keeping applied migration information.
78
     */
79
    public $migrationTable = '{{%migration}}';
80
    /**
81
     * @inheritdoc
82
     */
83
    public $templateFile = '@yii/views/migration.php';
84
    /**
85
     * @var array a set of template paths for generating migration code automatically.
86
     *
87
     * The key is the template type, the value is a path or the alias. Supported types are:
88
     * - `create_table`: table creating template
89
     * - `drop_table`: table dropping template
90
     * - `add_column`: adding new column template
91
     * - `drop_column`: dropping column template
92
     * - `create_junction`: create junction template
93
     *
94
     * @since 2.0.7
95
     */
96
    public $generatorTemplateFiles = [
97
        'create_table' => '@yii/views/createTableMigration.php',
98
        'drop_table' => '@yii/views/dropTableMigration.php',
99
        'add_column' => '@yii/views/addColumnMigration.php',
100
        'drop_column' => '@yii/views/dropColumnMigration.php',
101
        'create_junction' => '@yii/views/createTableMigration.php',
102
    ];
103
    /**
104
     * @var bool indicates whether the table names generated should consider
105
     * the `tablePrefix` setting of the DB connection. For example, if the table
106
     * name is `post` the generator wil return `{{%post}}`.
107
     * @since 2.0.8
108
     */
109
    public $useTablePrefix = false;
110
    /**
111
     * @var array column definition strings used for creating migration code.
112
     *
113
     * The format of each definition is `COLUMN_NAME:COLUMN_TYPE:COLUMN_DECORATOR`. Delimiter is `,`.
114
     * For example, `--fields="name:string(12):notNull:unique"`
115
     * produces a string column of size 12 which is not null and unique values.
116
     *
117
     * Note: primary key is added automatically and is named id by default.
118
     * If you want to use another name you may specify it explicitly like
119
     * `--fields="id_key:primaryKey,name:string(12):notNull:unique"`
120
     * @since 2.0.7
121
     */
122
    public $fields = [];
123
    /**
124
     * @var Connection|array|string the DB connection object or the application component ID of the DB connection to use
125
     * when applying migrations. Starting from version 2.0.3, this can also be a configuration array
126
     * for creating the object.
127
     */
128
    public $db = 'db';
129
130
131
    /**
132
     * @inheritdoc
133
     */
134 23
    public function options($actionID)
135
    {
136 23
        return array_merge(
137 23
            parent::options($actionID),
138 23
            ['migrationTable', 'db'], // global for all actions
139 23
            $actionID === 'create'
140 9
                ? ['templateFile', 'fields', 'useTablePrefix']
141 23
                : []
142
        );
143
    }
144
145
    /**
146
     * @inheritdoc
147
     * @since 2.0.8
148
     */
149
    public function optionAliases()
150
    {
151
        return array_merge(parent::optionAliases(), [
152
            'f' => 'fields',
153
            'p' => 'migrationPath',
154
            't' => 'migrationTable',
155
            'F' => 'templateFile',
156
            'P' => 'useTablePrefix',
157
        ]);
158
    }
159
160
    /**
161
     * This method is invoked right before an action is to be executed (after all possible filters.)
162
     * It checks the existence of the [[migrationPath]].
163
     * @param \yii\base\Action $action the action to be executed.
164
     * @return bool whether the action should continue to be executed.
165
     */
166 31
    public function beforeAction($action)
167
    {
168 31
        if (parent::beforeAction($action)) {
169 31
            if ($action->id !== 'create') {
170 23
                $this->db = Instance::ensure($this->db, Connection::className());
171
            }
172 31
            return true;
173
        } else {
174
            return false;
175
        }
176
    }
177
178
    /**
179
     * Creates a new migration instance.
180
     * @param string $class the migration class name
181
     * @return \yii\db\Migration the migration instance
182
     */
183 20
    protected function createMigration($class)
184
    {
185 20
        $this->includeMigrationFile($class);
186 20
        return new $class(['db' => $this->db]);
187
    }
188
189
    /**
190
     * @inheritdoc
191
     */
192 23
    protected function getMigrationHistory($limit)
193
    {
194 23
        if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
195 17
            $this->createMigrationHistoryTable();
196
        }
197 23
        $query = (new Query())
198 23
            ->select(['version', 'apply_time'])
199 23
            ->from($this->migrationTable)
200 23
            ->orderBy(['apply_time' => SORT_DESC, 'version' => SORT_DESC]);
201
202 23
        if (empty($this->migrationNamespaces)) {
203 16
            $query->limit($limit);
204 16
            $rows = $query->all($this->db);
205 16
            $history = ArrayHelper::map($rows, 'version', 'apply_time');
206 16
            unset($history[self::BASE_MIGRATION]);
207 16
            return $history;
208
        }
209
210 7
        $rows = $query->all($this->db);
211
212 7
        $history = [];
213 7
        foreach ($rows as $key => $row) {
214 7
            if ($row['version'] === self::BASE_MIGRATION) {
215 7
                continue;
216
            }
217 4
            if (preg_match('/m?(\d{6}_?\d{6})(\D.*)?$/is', $row['version'], $matches)) {
218 4
                $time = str_replace('_', '', $matches[1]);
219 4
                $row['canonicalVersion'] = $time;
220
            } else {
221
                $row['canonicalVersion'] = $row['version'];
222
            }
223 4
            $row['apply_time'] = (int) $row['apply_time'];
224 4
            $history[] = $row;
225
        }
226
227 7
        usort($history, function ($a, $b) {
228 4
            if ($a['apply_time'] === $b['apply_time']) {
229 4
                if (($compareResult = strcasecmp($b['canonicalVersion'], $a['canonicalVersion'])) !== 0) {
230 2
                    return $compareResult;
231
                }
232 2
                return strcasecmp($b['version'], $a['version']);
233
            }
234 1
            return ($a['apply_time'] > $b['apply_time']) ? -1 : +1;
235 7
        });
236
237 7
        $history = array_slice($history, 0, $limit);
238
239 7
        $history = ArrayHelper::map($history, 'version', 'apply_time');
240
241 7
        return $history;
242
    }
243
244
    /**
245
     * Creates the migration history table.
246
     */
247 17
    protected function createMigrationHistoryTable()
248
    {
249 17
        $tableName = $this->db->schema->getRawTableName($this->migrationTable);
250 17
        $this->stdout("Creating migration history table \"$tableName\"...", Console::FG_YELLOW);
251 17
        $this->db->createCommand()->createTable($this->migrationTable, [
252 17
            'version' => 'varchar(180) NOT NULL PRIMARY KEY',
253
            'apply_time' => 'integer',
254 17
        ])->execute();
255 17
        $this->db->createCommand()->insert($this->migrationTable, [
256 17
            'version' => self::BASE_MIGRATION,
257 17
            'apply_time' => time(),
258 17
        ])->execute();
259 17
        $this->stdout("Done.\n", Console::FG_GREEN);
260 17
    }
261
262
    /**
263
     * @inheritdoc
264
     */
265 22
    protected function addMigrationHistory($version)
266
    {
267 22
        $command = $this->db->createCommand();
268 22
        $command->insert($this->migrationTable, [
269 22
            'version' => $version,
270 22
            'apply_time' => time(),
271 22
        ])->execute();
272 22
    }
273
274
    /**
275
     * @inheritdoc
276
     */
277 12
    protected function removeMigrationHistory($version)
278
    {
279 12
        $command = $this->db->createCommand();
280 12
        $command->delete($this->migrationTable, [
281 12
            'version' => $version,
282 12
        ])->execute();
283 12
    }
284
285
    /**
286
     * @inheritdoc
287
     * @since 2.0.8
288
     */
289 9
    protected function generateMigrationSourceCode($params)
290
    {
291 9
        $parsedFields = $this->parseFields();
292 9
        $fields = $parsedFields['fields'];
293 9
        $foreignKeys = $parsedFields['foreignKeys'];
294
295 9
        $name = $params['name'];
296
297 9
        $templateFile = $this->templateFile;
298 9
        $table = null;
299 9
        if (preg_match('/^create_junction(?:_table_for_|_for_|_)(.+)_and_(.+)_tables?$/', $name, $matches)) {
300 1
            $templateFile = $this->generatorTemplateFiles['create_junction'];
301 1
            $firstTable = $matches[1];
302 1
            $secondTable = $matches[2];
303
304 1
            $fields = array_merge(
305
                [
306
                    [
307 1
                        'property' => $firstTable . '_id',
308 1
                        'decorators' => 'integer()',
309
                    ],
310
                    [
311 1
                        'property' => $secondTable . '_id',
312 1
                        'decorators' => 'integer()',
313
                    ],
314
                ],
315 1
                $fields,
316
                [
317
                    [
318
                        'property' => 'PRIMARY KEY(' .
319 1
                            $firstTable . '_id, ' .
320 1
                            $secondTable . '_id)',
321
                    ],
322
                ]
323
            );
324
325 1
            $foreignKeys[$firstTable . '_id']['table'] = $firstTable;
326 1
            $foreignKeys[$secondTable . '_id']['table'] = $secondTable;
327 1
            $foreignKeys[$firstTable . '_id']['column'] = null;
328 1
            $foreignKeys[$secondTable . '_id']['column'] = null;
329 1
            $table = $firstTable . '_' . $secondTable;
330 8
        } elseif (preg_match('/^add_(.+)_columns?_to_(.+)_table$/', $name, $matches)) {
331 1
            $templateFile = $this->generatorTemplateFiles['add_column'];
332 1
            $table = $matches[2];
333 7
        } elseif (preg_match('/^drop_(.+)_columns?_from_(.+)_table$/', $name, $matches)) {
334 1
            $templateFile = $this->generatorTemplateFiles['drop_column'];
335 1
            $table = $matches[2];
336 6
        } elseif (preg_match('/^create_(.+)_table$/', $name, $matches)) {
337 1
            $this->addDefaultPrimaryKey($fields);
338 1
            $templateFile = $this->generatorTemplateFiles['create_table'];
339 1
            $table = $matches[1];
340 6
        } elseif (preg_match('/^drop_(.+)_table$/', $name, $matches)) {
341 2
            $this->addDefaultPrimaryKey($fields);
342 2
            $templateFile = $this->generatorTemplateFiles['drop_table'];
343 2
            $table = $matches[1];
344
        }
345
346 9
        foreach ($foreignKeys as $column => $foreignKey) {
347 3
            $relatedColumn = $foreignKey['column'];
348 3
            $relatedTable = $foreignKey['table'];
349
            // Since 2.0.11 if related column name is not specified,
350
            // we're trying to get it from table schema
351
            // @see https://github.com/yiisoft/yii2/issues/12748
352 3
            if ($relatedColumn === null) {
353 3
                $relatedColumn = 'id';
354
                try {
355 3
                    $this->db = Instance::ensure($this->db, Connection::className());
356 3
                    $relatedTableSchema = $this->db->getTableSchema($relatedTable);
357 3
                    if ($relatedTableSchema !== null) {
358
                        $primaryKeyCount = count($relatedTableSchema->primaryKey);
359
                        if ($primaryKeyCount === 1) {
360
                            $relatedColumn = $relatedTableSchema->primaryKey[0];
361
                        } elseif ($primaryKeyCount > 1) {
362
                            $this->stdout("Related table for field \"{$column}\" exists, but primary key is composite. Default name \"id\" will be used for related field\n", Console::FG_YELLOW);
363
                        } elseif ($primaryKeyCount === 0) {
364
                            $this->stdout("Related table for field \"{$column}\" exists, but does not have a primary key. Default name \"id\" will be used for related field.\n", Console::FG_YELLOW);
365
                        }
366
                    }
367
                } catch (\ReflectionException $e) {
368
                    $this->stdout("Cannot initialize database component to try reading referenced table schema for field \"{$column}\". Default name \"id\" will be used for related field.\n", Console::FG_YELLOW);
369
                }
370
            }
371 3
            $foreignKeys[$column] = [
372 3
                'idx' => $this->generateTableName("idx-$table-$column"),
373 3
                'fk' => $this->generateTableName("fk-$table-$column"),
374 3
                'relatedTable' => $this->generateTableName($relatedTable),
375 3
                'relatedColumn' => $relatedColumn,
376
            ];
377
        }
378
379 9
        return $this->renderFile(Yii::getAlias($templateFile), array_merge($params, [
0 ignored issues
show
Bug introduced by
It seems like \Yii::getAlias($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...
380 9
            'table' => $this->generateTableName($table),
381 9
            'fields' => $fields,
382 9
            'foreignKeys' => $foreignKeys,
383
        ]));
384
    }
385
386
    /**
387
     * If `useTablePrefix` equals true, then the table name will contain the
388
     * prefix format.
389
     *
390
     * @param string $tableName the table name to generate.
391
     * @return string
392
     * @since 2.0.8
393
     */
394 9
    protected function generateTableName($tableName)
395
    {
396 9
        if (!$this->useTablePrefix) {
397 9
            return $tableName;
398
        }
399 2
        return '{{%' . $tableName . '}}';
400
    }
401
402
    /**
403
     * Parse the command line migration fields
404
     * @return array parse result with following fields:
405
     *
406
     * - fields: array, parsed fields
407
     * - foreignKeys: array, detected foreign keys
408
     *
409
     * @since 2.0.7
410
     */
411 9
    protected function parseFields()
412
    {
413 9
        $fields = [];
414 9
        $foreignKeys = [];
415
416 9
        foreach ($this->fields as $index => $field) {
417 4
            $chunks = preg_split('/\s?:\s?/', $field, null);
418 4
            $property = array_shift($chunks);
419
420 4
            foreach ($chunks as $i => &$chunk) {
421 4
                if (strpos($chunk, 'foreignKey') === 0) {
422 2
                    preg_match('/foreignKey\((\w*)\s?(\w*)\)/', $chunk, $matches);
423 2
                    $foreignKeys[$property] = [
424 2
                        'table' => isset($matches[1])
425 2
                            ? $matches[1]
426 2
                            : preg_replace('/_id$/', '', $property),
427 2
                        'column' => !empty($matches[2])
428
                            ? $matches[2]
429
                            : null,
430
                    ];
431
432 2
                    unset($chunks[$i]);
433 2
                    continue;
434
                }
435
436 4
                if (!preg_match('/^(.+?)\(([^(]+)\)$/', $chunk)) {
437 4
                    $chunk .= '()';
438
                }
439
            }
440 4
            $fields[] = [
441 4
                'property' => $property,
442 4
                'decorators' => implode('->', $chunks),
443
            ];
444
        }
445
446
        return [
447 9
            'fields' => $fields,
448 9
            'foreignKeys' => $foreignKeys,
449
        ];
450
    }
451
452
    /**
453
     * Adds default primary key to fields list if there's no primary key specified
454
     * @param array $fields parsed fields
455
     * @since 2.0.7
456
     */
457 2
    protected function addDefaultPrimaryKey(&$fields)
458
    {
459 2
        foreach ($fields as $field) {
460 2
            if (false !== strripos($field['decorators'], 'primarykey()')) {
461 1
                return;
462
            }
463
        }
464 2
        array_unshift($fields, ['property' => 'id', 'decorators' => 'primaryKey()']);
465 2
    }
466
}
467