-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathSerializedAttributes.php
84 lines (73 loc) · 2.93 KB
/
SerializedAttributes.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
<?php
namespace baibaratsky\yii\behaviors\model;
use yii\base\Behavior;
use yii\db\BaseActiveRecord;
/**
* Class SerializedAttributes
* @package baibaratsky\yii\behaviors\model
*
* @property BaseActiveRecord $owner
*/
class SerializedAttributes extends Behavior
{
/**
* @var string[] Attributes you want to be serialized
*/
public $attributes = [];
/**
* @var bool Encode serialized data to protect them from corruption (when your DB is not in UTF-8)
* @see http://www.jackreichert.com/2014/02/02/handling-a-php-unserialize-offset-error/
*/
public $encode = false;
private $oldAttributes = [];
public function events()
{
return [
BaseActiveRecord::EVENT_BEFORE_INSERT => 'serializeAttributes',
BaseActiveRecord::EVENT_BEFORE_UPDATE => 'serializeAttributes',
BaseActiveRecord::EVENT_AFTER_INSERT => 'deserializeAttributes',
BaseActiveRecord::EVENT_AFTER_UPDATE => 'deserializeAttributes',
BaseActiveRecord::EVENT_AFTER_FIND => 'deserializeAttributes',
BaseActiveRecord::EVENT_AFTER_REFRESH => 'deserializeAttributes',
];
}
public function serializeAttributes()
{
foreach ($this->attributes as $attribute) {
if (isset($this->oldAttributes[$attribute])) {
$this->owner->setOldAttribute($attribute, $this->oldAttributes[$attribute]);
}
if (is_array($this->owner->{$attribute}) && count($this->owner->{$attribute}) > 0) {
$this->owner->$attribute = serialize($this->owner->{$attribute});
if ($this->encode) {
$this->owner->{$attribute} = base64_encode($this->owner->{$attribute});
}
} elseif (empty($this->owner->{$attribute})) {
$this->owner->{$attribute} = null;
} else {
throw new SerializeAttributeException($this->owner, $attribute);
}
}
}
public function deserializeAttributes()
{
foreach ($this->attributes as $attribute) {
$this->oldAttributes[$attribute] = $this->owner->getOldAttribute($attribute);
if (empty($this->owner->{$attribute})) {
$this->owner->setAttribute($attribute, []);
$this->owner->setOldAttribute($attribute, []);
} elseif (is_scalar($this->owner->{$attribute})) {
if ($this->encode) {
$this->owner->{$attribute} = base64_decode($this->owner->{$attribute});
}
$value = @unserialize($this->owner->$attribute);
if ($value !== false) {
$this->owner->setAttribute($attribute, $value);
$this->owner->setOldAttribute($attribute, $value);
} else {
throw new DeserializeAttributeException($this->owner, $attribute);
}
}
}
}
}