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\Exception\JsonException; |
25: | use OpenSearch\Exception\RuntimeException; |
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 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 ($this->isJson($headers)) { |
60: | return $this->decode($data); |
61: | } |
62: | return $data; |
63: | } |
64: | |
65: | |
66: | |
67: | |
68: | |
69: | |
70: | private function decode(?string $data): array |
71: | { |
72: | if ($data === null || strlen($data) === 0) { |
73: | return []; |
74: | } |
75: | |
76: | try { |
77: | return json_decode($data, true, 512, JSON_THROW_ON_ERROR); |
78: | } catch (\JsonException $e) { |
79: | throw new JsonException($e->getCode(), $data, $e); |
80: | } |
81: | } |
82: | |
83: | |
84: | |
85: | |
86: | |
87: | |
88: | private function isJson(array $headers): bool |
89: | { |
90: | |
91: | if (array_key_exists('content_type', $headers)) { |
92: | return str_contains($headers['content_type'], 'json'); |
93: | } |
94: | |
95: | |
96: | $lowercaseHeaders = array_change_key_case($headers, CASE_LOWER); |
97: | if (array_key_exists('content-type', $lowercaseHeaders)) { |
98: | foreach ($lowercaseHeaders['content-type'] as $type) { |
99: | if (str_contains($type, 'json')) { |
100: | return true; |
101: | } |
102: | } |
103: | return false; |
104: | } |
105: | |
106: | |
107: | return true; |
108: | } |
109: | } |
110: | |