File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ namespace nullref \useful ;
4
+
5
+ use yii \base \Behavior ;
6
+ use yii \db \ActiveRecord ;
7
+
8
+ /**
9
+ * Class SerializeBehavior.
10
+ * Behavior for encoding and decoding model fields as storable representation of a value.
11
+ *
12
+ * @author Tenfrow <[email protected] >
13
+ * @copyright 2016 NullReferenceException
14
+ * @license MIT
15
+ */
16
+ class SerializeBehavior extends Behavior
17
+ {
18
+ public $ fields = [];
19
+
20
+ public function events ()
21
+ {
22
+ return [
23
+ ActiveRecord::EVENT_BEFORE_INSERT => 'encode ' ,
24
+ ActiveRecord::EVENT_BEFORE_UPDATE => 'encode ' ,
25
+ ActiveRecord::EVENT_AFTER_FIND => 'decode ' ,
26
+ ActiveRecord::EVENT_AFTER_INSERT => 'decode ' ,
27
+ ActiveRecord::EVENT_AFTER_UPDATE => 'decode ' ,
28
+ ];
29
+ }
30
+
31
+ public function encode ()
32
+ {
33
+ $ model = $ this ->owner ;
34
+ foreach ($ this ->fields as $ field ) {
35
+ if (isset ($ model ->$ field )) {
36
+ $ model ->$ field = serialize ($ model ->$ field );
37
+ }
38
+ }
39
+ }
40
+
41
+ public function decode ()
42
+ {
43
+ $ model = $ this ->owner ;
44
+ foreach ($ this ->fields as $ field ) {
45
+ $ model ->$ field = unserialize ($ model ->$ field );
46
+ }
47
+ }
48
+ }
You can’t perform that action at this time.
0 commit comments