-
Notifications
You must be signed in to change notification settings - Fork 139
Expand file tree
/
Copy pathJsonableBehavior.php
More file actions
230 lines (203 loc) · 5.84 KB
/
Copy pathJsonableBehavior.php
File metadata and controls
230 lines (203 loc) · 5.84 KB
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
<?php
namespace Queue\Model\Behavior;
use ArrayObject;
use Cake\Collection\CollectionInterface;
use Cake\Database\TypeFactory;
use Cake\Datasource\EntityInterface;
use Cake\Event\EventInterface;
use Cake\ORM\Behavior;
use Cake\ORM\Entity;
use Cake\ORM\Query\SelectQuery;
use InvalidArgumentException;
use Queue\Database\Type\ArrayType;
use RuntimeException;
/**
* A behavior that will json_encode (and json_decode) fields if they contain an array or specific pattern.
*
* @author Mark Scherer
* @license MIT
*/
class JsonableBehavior extends Behavior {
/**
* @var array<string, mixed>
*/
protected array $_defaultConfig = [
'fields' => [], // Fields to convert
'input' => 'array', // json, array, param, list (param/list only works with specific fields)
'output' => 'array', // json, array, param, list (param/list only works with specific fields)
'separator' => '|', // only for param or list
'keyValueSeparator' => ':', // only for param
'leftBound' => '{', // only for list
'rightBound' => '}', // only for list
'map' => [], // map on a different DB field
'encodeParams' => [ // params for json_encode
'options' => JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR,
'depth' => 512,
],
'decodeParams' => [ // params for json_decode
'assoc' => true, // useful when working with multidimensional arrays
'depth' => 512,
'options' => JSON_THROW_ON_ERROR,
],
];
/**
* @param array $config
*
* @throws \RuntimeException
*
* @return void
*/
public function initialize(array $config): void {
if (empty($this->_config['fields'])) {
throw new RuntimeException('Fields are required');
}
if (!is_array($this->_config['fields'])) {
$this->_config['fields'] = (array)$this->_config['fields'];
}
if (!is_array($this->_config['map'])) {
$this->_config['map'] = (array)$this->_config['map'];
}
if (!empty($this->_config['map']) && count($this->_config['fields']) !== count($this->_config['map'])) {
throw new RuntimeException('Fields and Map need to be of the same length if map is specified.');
}
foreach ($this->_config['fields'] as $field) {
if ($this->_table->getSchema()->getColumnType($field) !== 'json') {
$this->_table->getSchema()->setColumnType($field, 'json');
}
}
if ($this->_config['encodeParams']['options'] === null) {
$options = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_ERROR_INF_OR_NAN | JSON_PARTIAL_OUTPUT_ON_ERROR;
$this->_config['encodeParams']['options'] = $options;
}
TypeFactory::map('array', ArrayType::class);
}
/**
* Decode the fields on after find
*
* @param \Cake\Event\EventInterface $event
* @param \Cake\ORM\Query\SelectQuery $query
* @param \ArrayObject $options
* @param bool $primary
*
* @return void
*/
public function beforeFind(EventInterface $event, SelectQuery $query, ArrayObject $options, bool $primary): void {
$query->formatResults(function (CollectionInterface $results) {
return $results->map(function ($row) {
if (!$row instanceof Entity) {
return $row;
}
$this->decodeItems($row);
return $row;
});
});
}
/**
* Decodes the fields of an array/entity (if the value itself was encoded)
*
* @param \Cake\Datasource\EntityInterface $entity
*
* @return void
*/
public function decodeItems(EntityInterface $entity) {
$fields = $this->_getMappedFields();
foreach ($fields as $map => $field) {
$val = $entity->get($field);
if (is_string($val)) {
$val = $this->_fromJson($val);
}
$entity->set($map, $this->_decode($val));
}
}
/**
* Saves all fields that do not belong to the current Model into 'with' helper model.
*
* @param \Cake\Event\EventInterface $event
* @param \Cake\Datasource\EntityInterface $entity
* @param \ArrayObject $options
*
* @return void
*/
public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options): void {
$fields = $this->_getMappedFields();
foreach ($fields as $map => $field) {
if ($entity->get($map) === null) {
continue;
}
$val = $entity->get($map);
$entity->set($field, $this->_encode($val));
}
}
/**
* @return array
*/
protected function _getMappedFields() {
$usedFields = $this->_config['fields'];
$mappedFields = $this->_config['map'];
if (!$mappedFields) {
$mappedFields = $usedFields;
}
$fields = [];
foreach ($mappedFields as $index => $map) {
if (!$map || $map == $usedFields[$index]) {
$fields[$usedFields[$index]] = $usedFields[$index];
continue;
}
$fields[$map] = $usedFields[$index];
}
return $fields;
}
/**
* @param array|string $val
*
* @return string|null
*/
public function _encode($val) {
if (!empty($this->_config['fields']) && $this->_config['input'] === 'json') {
if (!is_string($val)) {
throw new InvalidArgumentException('Only accepts JSON string for input type `json`');
}
$val = $this->_fromJson($val);
}
if (!is_array($val)) {
return null;
}
$result = json_encode($val, $this->_config['encodeParams']['options'], $this->_config['encodeParams']['depth']);
if ($result === false) {
return null;
}
return $result;
}
/**
* Fields are absolutely necessary to function properly!
*
* @param array|null $val
*
* @return string|null
*/
public function _decode($val) {
if (!is_array($val)) {
return null;
}
$flags = $this->_config['encodeParams']['options'] | JSON_PRETTY_PRINT;
$decoded = json_encode($val, $flags, $this->_config['decodeParams']['depth']);
if ($decoded === false) {
return null;
}
return $decoded;
}
/**
* @param string $val
*
* @throws \InvalidArgumentException
*
* @return array
*/
protected function _fromJson(string $val): array {
$json = json_decode($val, true);
if (!is_array($json)) {
throw new InvalidArgumentException('Invalid JSON: ' . json_last_error_msg());
}
return $json;
}
}