-
Notifications
You must be signed in to change notification settings - Fork 2
/
SerializeAttributesBehavior.php
108 lines (84 loc) · 3.04 KB
/
SerializeAttributesBehavior.php
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
<?php
/**
* @author Vladimir Konchakovsky <[email protected]>
*/
namespace wowkaster\serializeAttributes;
use yii\behaviors\AttributeBehavior;
use yii\db\BaseActiveRecord;
use yii\helpers\Json;
class SerializeAttributesBehavior extends AttributeBehavior{
const DEFAULT_CONVERT_TYPE = 'serialize';
/**
* @var array
*/
private $allowConvertType = ['json', 'serialize'];
/**
* @var array
*/
public $convertAttr = [];
public function init() {
parent::init();
if (empty($this->attributes)) {
foreach($this->convertAttr as $key => $value) {
$attrName = is_scalar($key) ? $key : $value;
$convertType = is_scalar($key) ? $value : self::DEFAULT_CONVERT_TYPE;
if(!in_array($convertType, $this->allowConvertType)) {
throw new \Exception(strtr('Disallow type convert "{type}"', ['{type}' => $convertType]));
}
$this->attributes[BaseActiveRecord::EVENT_BEFORE_INSERT][] = $attrName;
$this->attributes[BaseActiveRecord::EVENT_BEFORE_UPDATE][] = $attrName;
$this->attributes[BaseActiveRecord::EVENT_AFTER_FIND][] = $attrName;
$this->attributes[BaseActiveRecord::EVENT_AFTER_INSERT][] = $attrName;
$this->attributes[BaseActiveRecord::EVENT_AFTER_UPDATE][] = $attrName;
}
}
}
/**
* @param \yii\base\Event $event
* @return string
*/
public function getValue($event) {
foreach($this->convertAttr as $key => $value) {
$attrName = is_scalar($key) ? $key : $value;
$convertType = is_scalar($key) ? $value : self::DEFAULT_CONVERT_TYPE;
$data = $this->owner->getAttribute($attrName);
if(in_array($event->name, [BaseActiveRecord::EVENT_BEFORE_INSERT, BaseActiveRecord::EVENT_BEFORE_UPDATE])) {
return $this->getConvertValue((array)$data, $convertType);
} elseif(in_array($event->name, [BaseActiveRecord::EVENT_AFTER_FIND, BaseActiveRecord::EVENT_AFTER_INSERT, BaseActiveRecord::EVENT_AFTER_UPDATE])) {
return $this->getUnConvertValue($data, $convertType);
} else {
return $data;
}
}
}
/**
* @param array $value
* @param $type
* @return string
*/
private function getConvertValue(array $value, $type) {
if($value && $type == self::DEFAULT_CONVERT_TYPE) {
$value = serialize($value);
} else {
$value = Json::encode($value);
}
return $value;
}
/**
* @param $value
* @param $type
* @return array
*/
private function getUnConvertValue($value, $type) {
if($value && $type == self::DEFAULT_CONVERT_TYPE) {
try {
$value = unserialize($value);
} catch(\Exception $e) {
trigger_error($e);
}
} else {
$value = Json::decode($value);
}
return $value;
}
}