Completed
Push — master ( b4d6a5...352f6d )
by Basil
02:42
created

MigrateController   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 4
dl 0
loc 54
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 9 2
A actionCreate() 0 32 5
1
<?php
2
3
namespace luya\console\commands;
4
5
use Yii;
6
use yii\helpers\Console;
7
use luya\helpers\FileHelper;
8
use yii\console\Exception;
9
10
/**
11
 * Database Migration Too.
12
 *
13
 * This extends the original yii migration tool by the ability to specify a module name within the create section.
14
 *
15
 * @author Basil Suter <[email protected]>
16
 * @since 1.0.0
17
 */
18
class MigrateController extends \yii\console\controllers\MigrateController
19
{
20
    /**
21
     * @inheritdoc
22
     */
23
    public function init()
24
    {
25
        parent::init();
26
        
27
        foreach (Yii::$app->modules as $key => $item) {
28
            $module = Yii::$app->getModule($key);
29
            $this->migrationPath[$key] = $module->getBasePath().DIRECTORY_SEPARATOR.'migrations';
30
        }
31
    }
32
    
33
    /**
34
     * @inheritDoc
35
     *
36
     * @see https://github.com/yiisoft/yii2/issues/384
37
     * @see \yii\console\controllers\BaseMigrateController::actionCreate()
38
     */
39
    public function actionCreate($name, $module = false)
40
    {
41
        if (empty($module)) {
42
            return parent::actionCreate($name);
43
        }
44
        
45
        if (!isset($this->migrationPath[$module])) {
46
            throw new Exception("The module \"$module\" does not exist in the application modules configuration.");
47
        }
48
        
49
        // apply custom migration code to generate new migrations for a module specific path
50
        if (!preg_match('/^[\w\\\\]+$/', $name)) {
51
            throw new Exception('The migration name should contain letters, digits, underscore and/or backslash characters only.');
52
        }
53
        
54
        $className = 'm'.gmdate('ymd_His').'_'.$name;
55
        
56
       
57
        $migrationPath = $this->migrationPath[$module];
58
        
59
        $file = $migrationPath . DIRECTORY_SEPARATOR . $className . '.php';
60
        if ($this->confirm("Create new migration '$file'?")) {
61
            $content = $this->generateMigrationSourceCode([
62
                'name' => $name,
63
                'className' => $className,
64
                'namespace' => null,
65
            ]);
66
            FileHelper::createDirectory($migrationPath);
67
            file_put_contents($file, $content);
68
            $this->stdout("New migration created successfully.\n", Console::FG_GREEN);
69
        }
70
    }
71
}
72