aboutsummaryrefslogtreecommitdiff
path: root/db/migrations/5.3.9_convert_aux_lock_rules_json_fields.php
blob: 56b1c2b571afa49c68d27695e8caefe2686933ee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
final class ConvertAuxLockRulesJsonFields extends Migration
{
    public function description()
    {
        return parent::description(); // TODO: Change the autogenerated stub
    }

    protected function up()
    {
        $query = "SELECT `lock_id`, `attributes`, `sorting` FROM `aux_lock_rules`";
        $rows = DBManager::get()->fetchAll($query);

        $query = "UPDATE `aux_lock_rules`
                  SET `attributes` = :attributes,
                      `sorting` = :sorting
                  WHERE `lock_id` = :id";
        $statement = DBManager::get()->prepare($query);

        foreach ($rows as $row) {
            $attributes = json_decode($row['attributes'], true) ?: [];
            $attributes = array_filter($attributes);
            $attributes = array_keys($attributes);

            $sorting = json_decode($row['sorting'], true) ?: [];
            $sorting = array_filter($sorting, function ($id) use ($attributes) {
                return in_array($id, $attributes);
            }, ARRAY_FILTER_USE_KEY);

            $statement->bindValue(':id', $row['lock_id']);
            $statement->bindValue(':attributes', json_encode($attributes));
            $statement->bindValue(':sorting', json_encode($sorting));
            $statement->execute();
        }
    }

    protected function down()
    {
        $query = "SELECT `lock_id`, `attributes` FROM `aux_lock_rules`";
        $rows = DBManager::get()->fetchAll($query);

        $query = "UPDATE `aux_lock_rules`
                  SET `attributes` = :attributes
                  WHERE `lock_id` = :id";
        $statement = DBManager::get()->prepare($query);

        foreach ($rows as $row) {
            $attributes = json_decode($row['attributes'], true) ?: [];
            $attributes = array_fill_keys($attributes, '1');

            $statement->bindValue(':id', $row['lock_id']);
            $statement->bindValue(':attributes', json_encode($attributes));
            $statement->execute();
        }
    }
}