Skip to content

Commit eb35a31

Browse files
committed
Add SerializeBehavior
1 parent 9101a1e commit eb35a31

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

src/SerializeBehavior.php

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
}

0 commit comments

Comments
 (0)