|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace ByTIC\DataObjects\Casts; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* Class AsArrayObject |
|
7
|
|
|
* @package ByTIC\DataObjects\Casts |
|
8
|
|
|
*/ |
|
9
|
|
|
class AsArrayObject implements Castable |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* Get the caster class to use when casting from / to this cast target. |
|
13
|
|
|
* |
|
14
|
|
|
* @param array $arguments |
|
15
|
|
|
* @return object|string |
|
16
|
|
|
*/ |
|
17
|
|
|
public static function castUsing(array $arguments) |
|
18
|
|
|
{ |
|
19
|
|
|
$encoder = isset($arguments[0]) ? $arguments[0] : null; |
|
20
|
|
|
return new class($encoder) implements CastsAttributes { |
|
|
|
|
|
|
21
|
|
|
|
|
22
|
|
|
protected $encoder = 'json'; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* constructor. |
|
26
|
|
|
* @param $encoder |
|
27
|
|
|
*/ |
|
28
|
|
|
public function __construct($encoder) |
|
29
|
|
|
{ |
|
30
|
|
|
$this->encoder = $encoder; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* @inheritDoc |
|
35
|
|
|
*/ |
|
36
|
|
|
public function get($model, $key, $value, $attributes): ArrayObject |
|
37
|
|
|
{ |
|
38
|
|
|
if (empty($value)) { |
|
39
|
|
|
$value = []; |
|
40
|
|
|
} else { |
|
41
|
|
|
$value = $this->decode($value); |
|
42
|
|
|
} |
|
43
|
|
|
return new ArrayObject($value); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
/** |
|
47
|
|
|
* @inheritDoc |
|
48
|
|
|
*/ |
|
49
|
|
|
public function set($model, $key, $value, $attributes) |
|
50
|
|
|
{ |
|
51
|
|
|
if (is_string($value)) { |
|
52
|
|
|
return [$key => $value]; |
|
53
|
|
|
} |
|
54
|
|
|
if ($value instanceof ArrayObject) { |
|
55
|
|
|
$value = $this->encode($value); |
|
56
|
|
|
} |
|
57
|
|
|
return [$key => $value]; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* @inheritDoc |
|
62
|
|
|
*/ |
|
63
|
|
|
public function serialize($model, string $key, $value, array $attributes) |
|
|
|
|
|
|
64
|
|
|
{ |
|
65
|
|
|
return $value->getArrayCopy(); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
/** |
|
69
|
|
|
* @param $value |
|
70
|
|
|
* @return false|string |
|
71
|
|
|
*/ |
|
72
|
|
|
protected function encode($value) |
|
73
|
|
|
{ |
|
74
|
|
|
if ($this->encoder == 'serialize') { |
|
75
|
|
|
return $value instanceof ArrayObject ? $value->serialize() : serialize($value); |
|
76
|
|
|
} |
|
77
|
|
|
return json_encode($value); |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
/** |
|
81
|
|
|
* @param $value |
|
82
|
|
|
* @return mixed |
|
83
|
|
|
*/ |
|
84
|
|
|
protected function decode($value) |
|
85
|
|
|
{ |
|
86
|
|
|
if ($this->encoder == 'serialize') { |
|
87
|
|
|
return unserialize($value); |
|
88
|
|
|
} |
|
89
|
|
|
return json_decode($value, true); |
|
90
|
|
|
} |
|
91
|
|
|
}; |
|
92
|
|
|
} |
|
93
|
|
|
} |
|
94
|
|
|
|
In the issue above, the returned value is violating the contract defined by the mentioned interface.
Let's take a look at an example: