-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonifyBehavior.php
108 lines (94 loc) · 2.27 KB
/
JsonifyBehavior.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
/**
* @link https://www.github.com/emidia/yii2-jsonify
* @copyright Copyright (c) 2015 E-midia Informações
* @license https://opensource.org/licenses/MIT
*/
namespace emidia\yii2\behaviors;
use yii\behaviors\AttributeBehavior;
use yii\base\InvalidConfigException;
use yii\db\BaseActiveRecord;
/**
* Behavior that convert array to JSON before save data in model
*
* To use JsonifyBehavior, insert the following code to your ActiveRecord class:
*
* ```php
* use emidia\yii2\JsonifyBehavior;
*
* public function behaviors()
* {
* return [
* JsonifyBehavior::className(),
* ];
* }
* ```
*
* By default JsonifyBehavior fill `json_data` attribute from array into a json encoded string
*
* If your attribute names are different, you may configure the [[attribute]]
* properties like the following:
*
* ```php
*
* public function behaviors()
* {
* return [
* [
* 'class' => JsonifyBehavior::className(),
* 'attribute' => 'data',
* ],
* ];
* }
*
* @author Rodrigo Zani <rodrigo.zhs@gmail.com>
*
*/
class JsonifyBehavior extends AttributeBehavior
{
/**
* @var string The attribute that will receive the JSON value
*/
public $attribute = 'json_data';
/**
*
* @var JSON constants
*
* The behaviour of these constants is described on the JSON constants page below.
* http://php.net/manual/en/json.constants.php
*
*/
public $jsonOptions = 0;
/**
* @var integer The 'deep' parameterin json_encode.
* Set the maximum depth. Must be greater than zero
*/
public $jsonDeep = 512;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if (empty($this->attributes)) {
$this->attributes = [
BaseActiveRecord::EVENT_BEFORE_VALIDATE => $this->attribute,
];
}
if ($this->attribute === null) {
throw new InvalidConfigException('Either "attribute" or "value" property must be specified.');
}
}
/**
* @inheritdoc
*/
protected function getValue($event)
{
$owner = $this->owner;
$json = '{}';
if (!empty($owner->{$this->attribute})) {
$json = json_encode($owner->{$this->attribute}, $this->jsonOptions, $this->jsonDeep);
}
return $json;
}
}