Passed
Push — master ( f96468...e8dc9f )
by M. Mikkel
03:43
created

m200720_194731_add_missing_audit_columns::safeUp()   A

Complexity

Conditions 6
Paths 17

Size

Total Lines 31
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 17
c 1
b 0
f 0
nc 17
nop 0
dl 0
loc 31
rs 9.0777
1
<?php
2
3
namespace mmikkel\cacheflag\migrations;
4
5
use Craft;
6
use craft\db\Migration;
7
8
use craft\helpers\Db;
9
use craft\helpers\StringHelper;
10
11
use mmikkel\cacheflag\records\Flags;
12
13
/**
14
 * Class m200721_194731_add_missing_audit_columns
15
 * @package mmikkel\cacheflag\migrations
16
 * @since 1.2.0
17
 */
18
class m200720_194731_add_missing_audit_columns extends Migration
19
{
20
21
    /**
22
     * @inheritDoc
23
     */
24
    public function safeUp()
25
    {
26
        // Don't make the same config changes twice
27
        $schemaVersion = Craft::$app->projectConfig
28
            ->get('plugins.cache-flag.schemaVersion', true);
29
30
        if (\version_compare($schemaVersion, '1.0.1', '>=')) {
31
            return;
32
        }
33
34
        $tableSchema = Craft::$app->db->schema->getTableSchema('{{%cacheflag_flags}}');
35
36
        // Make sure our audit columns exist
37
        if (!isset($tableSchema->columns['dateCreated'])) {
38
            $this->addColumn('{{%cacheflag_flags}}', 'dateCreated', $this->dateTime()->notNull());
39
        }
40
        if (!isset($tableSchema->columns['dateUpdated'])) {
41
            $this->addColumn('{{%cacheflag_flags}}', 'dateUpdated', $this->dateTime()->notNull());
42
        }
43
        if (!isset($tableSchema->columns['uid'])) {
44
            $this->addColumn('{{%cacheflag_flags}}', 'uid', $this->uid());
45
        }
46
47
        // Add missing UIDs to all rows in the flags table
48
        $rows = Flags::find()
49
            ->all();
50
        foreach ($rows as $row) {
51
            /** @var Flags $row */
52
            $row->dateCreated = $row->dateCreated ?? Db::prepareDateForDb(time());
53
            $row->uid = Db::uidById('{{%cacheflag_flags}}', (int)$row->id) ?? StringHelper::UUID();
54
            $row->save();
55
        }
56
57
    }
58
59
    /**
60
     * @inheritDoc
61
     */
62
    public function safeDown()
63
    {
64
        echo "m200720_194731_add_missing_audit_columns cannot be reverted.\n";
65
        return false;
66
    }
67
68
}
69