Passed
Push — master ( 6f5910...53ef6f )
by Josh
09:09 queued 11s
created

m200204_132923_FixBlockTypeSorting::safeDown()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
1
<?php
2
3
namespace angellco\spoon\migrations;
4
5
use angellco\spoon\records\BlockType;
6
use Craft;
7
use craft\db\Migration;
8
9
/**
10
 * m200204_132923_FixBlockTypeSorting migration.
11
 */
12
class m200204_132923_FixBlockTypeSorting extends Migration
13
{
14
    /**
15
     * @inheritdoc
16
     */
17
    public function safeUp()
18
    {
19
20
        if (!$this->db->columnExists('{{%spoon_blocktypes}}', 'groupSortOrder')) {
21
            $this->addColumn('{{%spoon_blocktypes}}', 'groupSortOrder', $this->smallInteger()->unsigned()->after('context'));
22
        }
23
24
        if (!$this->db->columnExists('{{%spoon_blocktypes}}', 'sortOrder')) {
25
            $this->addColumn('{{%spoon_blocktypes}}', 'sortOrder', $this->smallInteger()->unsigned()->after('groupSortOrder'));
26
        }
27
28
        // Update sort orders to match current state of the DB
29
        $records = BlockType::find()->all();
30
31
        $groupedByContext = [];
32
        foreach ($records as $record) {
33
            $groupedByContext[$record['context']][$record['groupName']][] = $record;
34
        }
35
36
        foreach ($groupedByContext as $recordGroups) {
37
38
            $groupSortOrder = 1;
39
            foreach ($recordGroups as $recordGroup) {
40
41
                $sortOrder = 1;
42
                /** @var BlockType $record */
43
                foreach ($recordGroup as $record) {
44
45
                    $record->groupSortOrder = $groupSortOrder;
46
                    $record->sortOrder = $sortOrder;
47
                    $record->save(false);
48
49
                    $sortOrder++;
50
                }
51
52
                $groupSortOrder++;
53
            }
54
55
        }
56
57
        Craft::$app->projectConfig->rebuild();
58
    }
59
60
    /**
61
     * @inheritdoc
62
     */
63
    public function safeDown()
64
    {
65
        echo "m200204_132923_FixBlockTypeSorting cannot be reverted.\n";
66
        return false;
67
    }
68
}
69