getContentTableRef()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
3
namespace flipbox\meta\migrations;
4
5
use craft\db\Migration;
6
use craft\helpers\MigrationHelper;
7
use craft\records\Field;
8
use flipbox\meta\fields\Meta;
9
use flipbox\meta\records\Meta as MetaRecord;
10
11
class m170720_092214_content_rename extends Migration
12
{
13
14
    /**
15
     * @param $val
16
     * @return string
17
     */
18
    private function getContentTableName($val)
19
    {
20
        return '{{%' . $this->getContentTableRef($val) . '}}';
21
    }
22
23
    /**
24
     * @param $val
25
     * @return string
26
     */
27
    private function getContentTableRef($val)
28
    {
29
        return MetaRecord::tableAlias() . 'content_' . $val;
30
    }
31
32
    /**
33
     * @inheritdoc
34
     */
35
    public function safeUp()
36
    {
37
        // find any of the context fields
38
        $records = Field::find()
39
            ->andWhere([
40
                'type' => Meta::class
41
            ])
42
            ->all();
43
44
        /** @var Field $record */
45
        foreach ($records as $record) {
46
            $oldTableName = $this->getContentTableName(strtolower($record->handle));
47
            $newTableName = $this->getContentTableName($record->id);
48
49
            // Remove legacy indexes
50
            MigrationHelper::dropAllForeignKeysOnTable($oldTableName, $this);
51
            MigrationHelper::dropAllIndexesOnTable($oldTableName, $this);
52
53
            // Rename table
54
            $this->renameTable($oldTableName, $newTableName);
55
56
            // New indexes and foreign keys
57
            $this->createIndex(
58
                $this->db->getIndexName($newTableName, 'elementId,siteId'),
59
                $newTableName,
60
                'elementId,siteId',
61
                true
62
            );
63
64
            $this->addForeignKey(
65
                $this->db->getForeignKeyName($newTableName, 'elementId'),
66
                $newTableName,
67
                'elementId',
68
                '{{%elements}}',
69
                'id',
70
                'CASCADE',
71
                null
72
            );
73
74
            $this->addForeignKey(
75
                $this->db->getForeignKeyName($newTableName, 'siteId'),
76
                $newTableName,
77
                'siteId',
78
                '{{%sites}}',
79
                'id',
80
                'CASCADE',
81
                'CASCADE'
82
            );
83
        }
84
85
        return true;
86
    }
87
88
    /**
89
     * @inheritdoc
90
     */
91
    public function safeDown()
92
    {
93
        echo "m170720_092214_content_rename cannot be reverted.\n";
94
95
        return false;
96
    }
97
}
98