1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Luminark\SerializableValues\Traits; |
4
|
|
|
|
5
|
|
|
trait HasSerializableValuesTrait |
6
|
|
|
{ |
7
|
|
|
protected function getSerializableAttributes() |
8
|
|
|
{ |
9
|
|
|
return []; |
10
|
|
|
} |
11
|
|
|
|
12
|
|
|
public function getValuesAttribute($values) |
13
|
|
|
{ |
14
|
|
|
return $this->unserialize($values); |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
public function setValuesAttribute(array $values) |
18
|
|
|
{ |
19
|
|
|
$values = array_merge($this->values, $values); |
|
|
|
|
20
|
|
|
$values = array_only($values, $this->getSerializableAttributes()); |
21
|
|
|
$this->attributes['values'] = $this->serialize($values); |
|
|
|
|
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
public function getOriginal($key = null, $default = null) |
25
|
|
|
{ |
26
|
|
|
$originalValues = $this->unserialize(parent::getOriginal('values')); |
27
|
|
|
if (array_key_exists($key, $originalValues)) { |
28
|
|
|
return array_get($originalValues, $key, $default); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
return array_get($this->original, $key, $default); |
|
|
|
|
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function fillableFromArray(array $attributes) |
35
|
|
|
{ |
36
|
|
|
return array_merge( |
37
|
|
|
parent::fillableFromArray($attributes), |
38
|
|
|
array_intersect_key($attributes, array_flip($this->getSerializableAttributes())) |
39
|
|
|
); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
public function isFillable($key) |
43
|
|
|
{ |
44
|
|
|
return in_array($key, $this->getSerializableAttributes()) |
45
|
|
|
? true |
46
|
|
|
: parent::isFillable($key); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function getAttribute($key) |
50
|
|
|
{ |
51
|
|
|
return in_array($key, $this->getSerializableAttributes()) |
52
|
|
|
? $this->getValue($key) |
53
|
|
|
: parent::getAttribute($key); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
public function setAttribute($key, $value) |
57
|
|
|
{ |
58
|
|
|
in_array($key, $this->getSerializableAttributes()) |
59
|
|
|
? $this->setValue($key, $value) |
60
|
|
|
: parent::setAttribute($key, $value); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public function getValue($key) |
64
|
|
|
{ |
65
|
|
|
return array_get($this->getAttribute('values'), $key); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
public function setValue($key, $value) |
69
|
|
|
{ |
70
|
|
|
$values = $this->values; |
71
|
|
|
$values[$key] = $value; |
72
|
|
|
$this->setValuesAttribute($values); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
protected function serialize($array) |
76
|
|
|
{ |
77
|
|
|
return base64_encode(serialize($array ?: [])); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
protected function unserialize($string) |
81
|
|
|
{ |
82
|
|
|
return $string ? unserialize(base64_decode($string)) : []; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: