Completed
Push — master ( f95aab...ce10dc )
by Basil
04:32
created

JsonBehavior::events()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
c 0
b 0
f 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
3
namespace luya\behaviors;
4
5
use yii\base\Behavior;
6
use yii\db\ActiveRecord;
7
use luya\helpers\Json;
8
9
/**
10
 * Json Behavior.
11
 * 
12
 * Provides auto encoding for array values after validation in order to store in the database.
13
 * 
14
 * @author Basil Suter <[email protected]>
15
 * @since 1.0.9
16
 */
17
class JsonBehavior extends Behavior
18
{
19
    public $attributes = [];
20
    
21
    /**
22
     * @inheritdoc
23
     */
24
    public function events()
25
    {
26
        return [
27
            ActiveRecord::EVENT_AFTER_VALIDATE => 'autoEncodeAttributes',
28
        ];
29
    }
30
    
31
    /**
32
     * Encode attributes.
33
     */
34
    public function autoEncodeAttributes()
35
    {
36
        foreach ($this->attributes as $name) {
37
            if (!isset($this->owner->getDirtyAttributes()[$name])) {
38
                continue;
39
            }
40
            
41
            $value = $this->owner->{$name};
42
            
43
            if (is_array($value)) {
44
                $this->owner->{$name} = $this->jsonEncode($name);
45
            }
46
        }
47
    }
48
    
49
    /**
50
     * Encodes the given value into a JSON string.
51
     * 
52
     * @param mixed $value This is commonly an array.
53
     * @return string
54
     */
55
    public function jsonEncode($value)
56
    {
57
        return Json::encode($value);
58
    }
59
    
60
    /**
61
     * Decodes the given JSON string into a PHP data structure.
62
     * 
63
     * @param string $value
64
     * @return array
65
     */
66
    public function jsonDecode($value)
67
    {
68
        return Json::decode($value);
69
    }
70
}