Passed
Push — master ( e0e6c6...849d03 )
by Roman
02:16
created

M180310000001JobJsonData   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 11
dl 0
loc 65
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A safeDown() 0 3 1
B serializeData() 0 16 5
B safeUp() 0 30 5
1
<?php
2
/**
3
 * @link https://github.com/zhuravljov/yii2-queue-monitor
4
 * @copyright Copyright (c) 2017 Roman Zhuravlev
5
 * @license http://opensource.org/licenses/BSD-3-Clause
6
 */
7
8
namespace zhuravljov\yii\queue\monitor\migrations;
9
10
use yii\db\Query;
11
use yii\helpers\Json;
12
use zhuravljov\yii\queue\monitor\base\Migration;
13
14
/**
15
 * Job Json Data
16
 *
17
 * @author Roman Zhuravlev <[email protected]>
18
 */
19
class M180310000001JobJsonData extends Migration
20
{
21
    /**
22
     * @inheritdoc
23
     */
24
    public function safeUp()
25
    {
26
        $this->renameColumn(
27
            $this->env->pushTableName,
28
            'job_object',
29
            'job_data'
30
        );
31
32
        $time = $this->beginCommand("update {$this->env->pushTableName}");
33
        $this->compact = true;
34
        $query = (new Query())->from($this->env->pushTableName);
35
        foreach ($query->each(1000, $this->db) as $row) {
36
            if (is_resource($row['job_data'])) {
37
                $row['job_data'] = stream_get_contents($row['job_data']);
38
            }
39
            $job = unserialize($row['job_data']);
40
            $data = [];
41
            foreach (get_object_vars($job) as $property => $value) {
42
                if ($property !== '__PHP_Incomplete_Class_Name') {
43
                    $data[$property] = $this->serializeData($value);
44
                }
45
            }
46
            $this->update(
47
                $this->env->pushTableName,
48
                ['job_data' => Json::encode($data)],
49
                ['id' => $row['id']]
50
            );
51
        }
52
        $this->compact = false;
53
        $this->endCommand($time);
54
    }
55
56
    /**
57
     * @inheritdoc
58
     */
59
    public function safeDown()
60
    {
61
        return false;
62
    }
63
64
    /**
65
     * @param mixed $data
66
     * @return mixed
67
     */
68
    private function serializeData($data)
69
    {
70
        if (is_object($data)) {
71
            $result = ['=class=' => get_class($data)];
72
            foreach (get_object_vars($data) as $property => $value) {
73
                $result[$property] = $this->serializeData($value);
74
            }
75
            return $result;
76
        }
77
        if (is_array($data)) {
78
            $result = [];
79
            foreach ($data as $key => $value) {
80
                $result[$key] = $this->serializeData($value);
81
            }
82
        }
83
        return $data;
84
    }
85
}
86