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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\queue\serializers;
use Yii;
use yii\base\BaseObject;
use yii\base\InvalidConfigException;
use yii\helpers\Json;
/**
* Json Serializer.
*
* @author Roman Zhuravlev <zhuravljov@gmail.com>
*/
class JsonSerializer extends BaseObject implements SerializerInterface
{
/**
* @var string
*/
public $classKey = 'class';
/**
* @var int
*/
public $options = 0;
/**
* @inheritdoc
*/
public function serialize($job)
{
return Json::encode($this->toArray($job), $this->options);
}
/**
* @inheritdoc
*/
public function unserialize($serialized)
{
return $this->fromArray(Json::decode($serialized));
}
/**
* @param mixed $data
* @return array|mixed
* @throws InvalidConfigException
*/
protected function toArray($data)
{
if (is_object($data)) {
$result = [$this->classKey => get_class($data)];
foreach (get_object_vars($data) as $property => $value) {
if ($property === $this->classKey) {
throw new InvalidConfigException("Object cannot contain $this->classKey property.");
}
$result[$property] = $this->toArray($value);
}
return $result;
}
if (is_array($data)) {
$result = [];
foreach ($data as $key => $value) {
if ($key === $this->classKey) {
throw new InvalidConfigException("Array cannot contain $this->classKey key.");
}
$result[$key] = $this->toArray($value);
}
return $result;
}
return $data;
}
/**
* @param array $data
* @return mixed
*/
protected function fromArray($data)
{
if (!is_array($data)) {
return $data;
}
if (!isset($data[$this->classKey])) {
$result = [];
foreach ($data as $key => $value) {
$result[$key] = $this->fromArray($value);
}
return $result;
}
$config = ['class' => $data[$this->classKey]];
unset($data[$this->classKey]);
foreach ($data as $property => $value) {
$config[$property] = $this->fromArray($value);
}
return Yii::createObject($config);
}
}