IntegrationConnectionNameColumn::tableName()
last analyzed

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
c 0
b 0
f 0
ccs 0
cts 0
cp 0
nc 1
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipboxfactory/craft-integration/blob/master/LICENSE
6
 * @link       https://github.com/flipboxfactory/craft-integration/
7
 */
8
9
namespace flipbox\craft\integration\migrations;
10
11
use Craft;
12
use craft\db\Migration;
13
use craft\helpers\StringHelper;
14
use yii\db\Query;
15
16
/**
17
 * @author Flipbox Factory <[email protected]>
18
 * @since 2.0.0
19
 */
20
abstract class IntegrationConnectionNameColumn extends Migration
21
{
22
    /**
23
     * @return string
24
     */
25
    abstract protected static function tableName(): string;
26
27
    /**
28
     * @inheritdoc
29
     * @throws \yii\base\NotSupportedException
30
     * @throws \yii\db\Exception
31
     */
32
    public function safeUp()
33
    {
34
        $table = $this->getDb()->getSchema()->getTableSchema(
35
            $this->getDb()->getSchema()->getRawTableName(static::tableName())
36
        );
37
38
        if (isset($table->columns['name'])) {
39
            return true;
40
        }
41
42
        $this->addColumn(
43
            static::tableName(),
44
            'name',
45
            $this->string()->after('id')->notNull()
46
        );
47
48
        $records = (new Query())
49
            ->from(static::tableName())
50
            ->select(['id', 'handle'])
51
            ->all();
52
53
        foreach ($records as $record) {
54
            Craft::$app->getDb()->createCommand()
55
                ->update(
56
                    static::tableName(),
57
                    ['name' => StringHelper::titleize($record['handle'])],
58
                    ['id' => $record['id']]
59
                )
60
                ->execute();
61
        }
62
    }
63
}
64