1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace SubjectivePHP\Psr\SimpleCache\Serializer; |
4
|
|
|
|
5
|
|
|
use SubjectivePHP\Psr\SimpleCache\InvalidArgumentException; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Uses native php serialize functions for serializing data. |
9
|
|
|
*/ |
10
|
|
|
final class BasicSerializer implements SerializerInterface |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* Unserializes cached data into the original state. |
14
|
|
|
* |
15
|
|
|
* @param mixed $data The data to unserialize. |
16
|
|
|
* |
17
|
|
|
* @return mixed |
18
|
|
|
* |
19
|
|
|
* @throws InvalidArgumentException Thrown if the given value cannot be unserialized. |
20
|
|
|
*/ |
21
|
|
|
public function unserialize($data) |
22
|
|
|
{ |
23
|
|
|
$this->throwIfTrue(!is_string($data), '$data must be a string'); |
24
|
|
|
|
25
|
|
|
set_error_handler($this->getErrorHandler()); |
26
|
|
|
try { |
27
|
|
|
$unserialized = unserialize($data); |
28
|
|
|
$this->throwIfTrue($unserialized === false, '$data could not be unserialized'); |
29
|
|
|
return $unserialized; |
30
|
|
|
} finally { |
31
|
|
|
restore_error_handler(); |
32
|
|
|
} |
33
|
|
|
}//@codeCoverageIgnore |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Serializes the given data for storage in caching. |
37
|
|
|
* |
38
|
|
|
* @param mixed $value The data to serialize for caching. |
39
|
|
|
* |
40
|
|
|
* @return mixed The result of serializing the given $data. |
41
|
|
|
* |
42
|
|
|
* @throws InvalidArgumentException Thrown if the given value cannot be serialized for caching. |
43
|
|
|
*/ |
44
|
|
|
public function serialize($value) |
45
|
|
|
{ |
46
|
|
|
try { |
47
|
|
|
return serialize($value); |
48
|
|
|
} catch (\Throwable $t) { |
49
|
|
|
throw new InvalidArgumentException($t->getMessage(), 0, $t); |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
private function throwIfTrue(bool $condition, string $message) |
54
|
|
|
{ |
55
|
|
|
if ($condition) { |
56
|
|
|
throw new InvalidArgumentException($message); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
private function getErrorHandler() : callable |
61
|
|
|
{ |
62
|
|
|
return function ($level, $message, $file, $line) { |
|
|
|
|
63
|
|
|
throw new InvalidArgumentException($message, $level); |
64
|
|
|
}; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.