Passed
Push — master ( 758032...380927 )
by Benjamin
28:34 queued 21:24
created

m180529_125418_info::safeUp()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace dukt\analytics\migrations;
4
5
use craft\db\Migration;
6
use craft\db\Query;
7
use craft\helpers\Json;
8
use dukt\analytics\models\Info;
9
use dukt\analytics\Plugin;
10
11
/**
12
 * m180529_125418_info migration.
13
 */
14
class m180529_125418_info extends Migration
15
{
16
    /**
17
     * @inheritdoc
18
     */
19
    public function safeUp()
20
    {
21
        $this->createTables();
22
        $this->insertDefaultData();
23
    }
24
25
    /**
26
     * Creates the tables.
27
     */
28
    public function createTables()
29
    {
30
        $this->createTable(
31
            '{{%analytics_info}}',
32
            [
33
                'id' => $this->primaryKey(),
34
                'forceConnect' => $this->boolean()->defaultValue(false)->notNull(),
35
                'token' => $this->text(),
36
37
                'dateCreated' => $this->dateTime()->notNull(),
38
                'dateUpdated' => $this->dateTime()->notNull(),
39
                'uid' => $this->uid()
40
            ]
41
        );
42
    }
43
44
    /**
45
     * Populates the DB with the default data.
46
     */
47
    public function insertDefaultData()
48
    {
49
        $forceConnect = false;
50
        $token = null;
51
        $settings = null;
52
53
        $row = (new Query())
54
            ->select('*')
55
            ->from(['{{%plugins}}'])
56
            ->where(['handle' => 'analytics'])
57
            ->one();
58
59
        if ($row) {
60
            $settingsJson = $row['settings'];
61
            $settings = Json::decode($settingsJson);
62
        }
63
64
        if($settings) {
65
            $forceConnect = $settings['forceConnect'];
66
            $token = $settings['token'];
67
        }
68
69
        // Populate the analytics_info table
70
        echo '    > populate the analytics_info table ...';
71
        Plugin::getInstance()->saveInfo(new Info([
72
            'forceConnect' => $forceConnect,
73
            'token' => $token,
74
        ]));
75
        echo " done\n";
76
77
        // Get rid of the old plugin settings
78
        echo '    > remove old plugin settings ...';
79
        if($settings) {
80
            unset($settings['forceConnect'], $settings['token']);
81
            $settingsJson = Json::encode($settings);
82
            $this->update('{{%plugins}}', ['settings' => $settingsJson], ['id' => $row['id']]);
83
        }
84
        echo " done\n";
85
    }
86
87
    /**
88
     * @inheritdoc
89
     */
90
    public function safeDown()
91
    {
92
        echo "m180529_125418_info cannot be reverted.\n";
93
        return false;
94
    }
95
}
96