1 | <?php |
||
2 | |||
3 | /* |
||
4 | * This file is part of the Cache package. |
||
5 | * |
||
6 | * Copyright (c) Daniel González |
||
7 | * |
||
8 | * For the full copyright and license information, please view the LICENSE |
||
9 | * file that was distributed with this source code. |
||
10 | * |
||
11 | * @author Daniel González <[email protected]> |
||
12 | * @author Arnold Daniels <[email protected]> |
||
13 | */ |
||
14 | |||
15 | declare(strict_types=1); |
||
16 | |||
17 | namespace Desarrolla2\Cache\Packer; |
||
18 | |||
19 | use Desarrolla2\Cache\Packer\PackerInterface; |
||
20 | use Desarrolla2\Cache\Exception\InvalidArgumentException; |
||
21 | |||
22 | /** |
||
23 | * Pack value through serialization |
||
24 | */ |
||
25 | class JsonPacker implements PackerInterface |
||
26 | { |
||
27 | /** |
||
28 | * Get cache type (might be used as file extension) |
||
29 | * |
||
30 | * @return string |
||
31 | */ |
||
32 | public function getType() |
||
33 | { |
||
34 | return 'json'; |
||
35 | } |
||
36 | |||
37 | /** |
||
38 | * Pack the value |
||
39 | * |
||
40 | * @param mixed $value |
||
41 | * @return string |
||
42 | */ |
||
43 | public function pack($value) |
||
44 | { |
||
45 | return json_encode($value); |
||
46 | } |
||
47 | |||
48 | /** |
||
49 | * Unpack the value |
||
50 | * |
||
51 | * @param string $packed |
||
52 | * @return mixed |
||
53 | * @throws InvalidArgumentException |
||
54 | */ |
||
55 | public function unpack($packed) |
||
56 | { |
||
57 | if (!is_string($packed)) { |
||
0 ignored issues
–
show
introduced
by
![]() |
|||
58 | throw new InvalidArgumentException("packed value should be a string"); |
||
59 | } |
||
60 | |||
61 | $ret = json_decode($packed); |
||
62 | |||
63 | if (!isset($ret) && json_last_error()) { |
||
64 | throw new \UnexpectedValueException("packed value is not a valid JSON string"); |
||
65 | } |
||
66 | |||
67 | return $ret; |
||
68 | } |
||
69 | } |
||
70 |