4
4
5
5
use yii \base \Behavior ;
6
6
use yii \db \ActiveRecord ;
7
+ use yii \helpers \ArrayHelper ;
7
8
use yii \helpers \Json ;
8
9
9
10
/**
25
26
* }
26
27
* ~~~
27
28
*
29
+ * @property ActiveRecord $owner
30
+ *
28
31
* @package frostealth\yii2\behaviors
29
32
*/
30
33
class ArrayFieldBehavior extends Behavior
@@ -44,13 +47,25 @@ class ArrayFieldBehavior extends Behavior
44
47
*/
45
48
public $ defaultDecodedValue = [];
46
49
50
+ /**
51
+ * @var array
52
+ */
53
+ private $ _cache = [];
54
+
55
+ /**
56
+ * @var array
57
+ */
58
+ private $ _oldAttributes = [];
59
+
47
60
/**
48
61
* @inheritdoc
49
62
*/
50
63
public function events ()
51
64
{
52
65
return [
53
66
ActiveRecord::EVENT_AFTER_FIND => 'decode ' ,
67
+ ActiveRecord::EVENT_AFTER_INSERT => 'decode ' ,
68
+ ActiveRecord::EVENT_AFTER_UPDATE => 'decode ' ,
54
69
ActiveRecord::EVENT_BEFORE_UPDATE => 'encode ' ,
55
70
ActiveRecord::EVENT_BEFORE_INSERT => 'encode ' ,
56
71
];
@@ -62,10 +77,16 @@ public function events()
62
77
public function encode ()
63
78
{
64
79
foreach ($ this ->attributes as $ attribute ) {
65
- $ value = $ this ->owner ->{$ attribute };
66
- $ value = !empty ($ value ) ? Json::encode ($ value ) : $ this ->defaultEncodedValue ;
80
+ if (!$ this ->owner ->getIsNewRecord ()) {
81
+ $ oldValue = ArrayHelper::getValue ($ this ->_oldAttributes , $ this ->defaultEncodedValue );
82
+ $ this ->owner ->setOldAttribute ($ attribute , $ oldValue );
83
+ }
84
+
85
+ $ value = $ this ->owner ->getAttribute ($ attribute );
86
+ $ this ->_cache [$ attribute ] = $ value ;
67
87
68
- $ this ->owner ->{$ attribute } = $ value ;
88
+ $ value = !empty ($ value ) ? Json::encode ($ value ) : $ this ->defaultEncodedValue ;
89
+ $ this ->owner ->setAttribute ($ attribute , $ value );
69
90
}
70
91
}
71
92
@@ -75,9 +96,21 @@ public function encode()
75
96
public function decode ()
76
97
{
77
98
foreach ($ this ->attributes as $ attribute ) {
78
- $ value = Json::decode ($ this ->owner ->{$ attribute });
99
+ if (!empty ($ this ->_cache [$ attribute ])) {
100
+ $ value = $ this ->_cache [$ attribute ];
101
+ } else {
102
+ $ value = Json::decode ($ this ->owner ->getAttribute ($ attribute ));
103
+ }
104
+
105
+ $ value = !empty ($ value ) ? $ value : $ this ->defaultDecodedValue ;
106
+ $ this ->owner ->setAttribute ($ attribute , $ value );
79
107
80
- $ this ->owner ->{$ attribute } = !empty ($ value ) ? $ value : $ this ->defaultDecodedValue ;
108
+ if (!$ this ->owner ->getIsNewRecord ()) {
109
+ $ this ->_oldAttributes [$ attribute ] = $ this ->owner ->getOldAttribute ($ attribute );
110
+ $ this ->owner ->setOldAttribute ($ attribute , $ value );
111
+ }
81
112
}
113
+
114
+ $ this ->_cache = [];
82
115
}
83
116
}
0 commit comments