-
Notifications
You must be signed in to change notification settings - Fork 178
Expand file tree
/
Copy pathHasJsonable.php
More file actions
89 lines (78 loc) · 2.01 KB
/
HasJsonable.php
File metadata and controls
89 lines (78 loc) · 2.01 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
<?php namespace October\Rain\Database\Concerns;
/**
* HasJsonable concern for a model
*
* @package october\database
* @author Alexey Bobkov, Samuel Georges
*/
trait HasJsonable
{
/**
* @var array jsonable attribute names that are json encoded and decoded from the database
*/
protected $jsonable = [];
/**
* addJsonable attributes for the model.
*
* @param array|string|null $attributes
* @return void
*/
public function addJsonable($attributes = null)
{
$attributes = is_array($attributes) ? $attributes : func_get_args();
$this->jsonable = array_merge($this->jsonable, $attributes);
}
/**
* isJsonable checks if an attribute is jsonable or not.
*
* @return array
*/
public function isJsonable($key)
{
return in_array($key, $this->jsonable);
}
/**
* getJsonable attributes name
*
* @return array
*/
public function getJsonable()
{
return $this->jsonable;
}
/**
* jsonable attributes set for the model.
*
* @param array $jsonable
* @return $this
*/
public function jsonable(array $jsonable)
{
$this->jsonable = $jsonable;
return $this;
}
/**
* addJsonableAttributesToArray
* @return array
*/
protected function addJsonableAttributesToArray(array $attributes, array $mutatedAttributes)
{
foreach ($this->jsonable as $key) {
if (
!array_key_exists($key, $attributes) ||
in_array($key, $mutatedAttributes)
) {
continue;
}
// Prevent double decoding of jsonable attributes.
if (!is_string($attributes[$key])) {
continue;
}
$jsonValue = json_decode($attributes[$key], true);
if (json_last_error() === JSON_ERROR_NONE) {
$attributes[$key] = $jsonValue;
}
}
return $attributes;
}
}