|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace SubjectivePHP\Psr\SimpleCache\Serializer; |
|
4
|
|
|
|
|
5
|
|
|
use SubjectivePHP\Psr\SimpleCache\InvalidArgumentException; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Serializer implementation responsible for serializing and unserializing data to and from json. |
|
9
|
|
|
*/ |
|
10
|
|
|
final class JsonSerializer implements SerializerInterface |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* @var boolean |
|
14
|
|
|
*/ |
|
15
|
|
|
private $decodeAsAssoc = true; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @var integer |
|
19
|
|
|
*/ |
|
20
|
|
|
private $encodeOptions = 0; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* Construct a new JsonSerializer. |
|
24
|
|
|
* |
|
25
|
|
|
* @param boolean $decodeAsAssoc When TRUE, returned objects will be converted into associative arrays. |
|
26
|
|
|
* @param integer $encodeOptions Bitmask consisting of json endoding options. |
|
27
|
|
|
*/ |
|
28
|
|
|
public function __construct(bool $decodeAsAssoc = true, int $encodeOptions = 0) |
|
29
|
|
|
{ |
|
30
|
|
|
$this->decodeAsAssoc = $decodeAsAssoc; |
|
31
|
|
|
$this->encodeOptions = $encodeOptions; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Unserializes cached data into the original state. |
|
36
|
|
|
* |
|
37
|
|
|
* @param mixed $data The data to unserialize. |
|
38
|
|
|
* |
|
39
|
|
|
* @return mixed |
|
40
|
|
|
* |
|
41
|
|
|
* @throws InvalidArgumentException Thrown if the given value cannot be unserialized. |
|
42
|
|
|
*/ |
|
43
|
|
|
public function unserialize($data) |
|
44
|
|
|
{ |
|
45
|
|
|
try { |
|
46
|
|
|
return json_decode($data, $this->decodeAsAssoc); |
|
47
|
|
|
} finally { |
|
48
|
|
|
$this->ensureJson(); |
|
49
|
|
|
} |
|
50
|
|
|
}//@codeCoverageIgnore |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* Serializes the given data for storage in caching. |
|
54
|
|
|
* |
|
55
|
|
|
* @param mixed $value The data to serialize for caching. |
|
56
|
|
|
* |
|
57
|
|
|
* @return mixed The result of serializing the given $data. |
|
58
|
|
|
* |
|
59
|
|
|
* @throws InvalidArgumentException Thrown if the given value cannot be serialized for caching. |
|
60
|
|
|
*/ |
|
61
|
|
|
public function serialize($value) |
|
62
|
|
|
{ |
|
63
|
|
|
try { |
|
64
|
|
|
return json_encode($value, $this->encodeOptions); |
|
65
|
|
|
} finally { |
|
66
|
|
|
$this->ensureJson(); |
|
67
|
|
|
} |
|
68
|
|
|
}//@codeCoverageIgnore |
|
69
|
|
|
|
|
70
|
|
|
private function ensureJson() |
|
71
|
|
|
{ |
|
72
|
|
|
if (json_last_error() !== JSON_ERROR_NONE) { |
|
73
|
|
|
throw new InvalidArgumentException(json_last_error_msg()); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|