1: | <?php |
2: | |
3: | declare(strict_types=1); |
4: | |
5: | |
6: | |
7: | |
8: | |
9: | |
10: | |
11: | |
12: | |
13: | |
14: | |
15: | |
16: | |
17: | |
18: | |
19: | |
20: | |
21: | |
22: | namespace OpenSearch\Serializers; |
23: | |
24: | use OpenSearch\Common\Exceptions; |
25: | use OpenSearch\Common\Exceptions\Serializer\JsonErrorException; |
26: | |
27: | if (!defined('JSON_INVALID_UTF8_SUBSTITUTE')) { |
28: | |
29: | define('JSON_INVALID_UTF8_SUBSTITUTE', 0); |
30: | } |
31: | |
32: | class SmartSerializer implements SerializerInterface |
33: | { |
34: | |
35: | |
36: | |
37: | public function serialize($data): string |
38: | { |
39: | if (is_string($data) === true) { |
40: | return $data; |
41: | } else { |
42: | $data = json_encode($data, JSON_PRESERVE_ZERO_FRACTION + JSON_INVALID_UTF8_SUBSTITUTE); |
43: | if ($data === false) { |
44: | throw new Exceptions\RuntimeException("Failed to JSON encode: ".json_last_error_msg()); |
45: | } |
46: | if ($data === '[]') { |
47: | return '{}'; |
48: | } else { |
49: | return $data; |
50: | } |
51: | } |
52: | } |
53: | |
54: | |
55: | |
56: | |
57: | public function deserialize(?string $data, array $headers) |
58: | { |
59: | if (isset($headers['content_type']) === true) { |
60: | if (strpos($headers['content_type'], 'json') !== false) { |
61: | return $this->decode($data); |
62: | } else { |
63: | |
64: | return $data; |
65: | } |
66: | } else { |
67: | |
68: | return $this->decode($data); |
69: | } |
70: | } |
71: | |
72: | |
73: | |
74: | |
75: | |
76: | |
77: | |
78: | private function decode(?string $data): array |
79: | { |
80: | if ($data === null || strlen($data) === 0) { |
81: | return []; |
82: | } |
83: | |
84: | try { |
85: | return json_decode($data, true, 512, JSON_THROW_ON_ERROR); |
86: | } catch (\JsonException $e) { |
87: | throw new JsonErrorException($e->getCode(), $data, []); |
88: | } |
89: | } |
90: | } |
91: | |