1: <?php
2:
3: declare(strict_types=1);
4:
5: /**
6: * Copyright OpenSearch Contributors
7: * SPDX-License-Identifier: Apache-2.0
8: *
9: * OpenSearch PHP client
10: *
11: * @link https://github.com/opensearch-project/opensearch-php/
12: * @copyright Copyright (c) Elasticsearch B.V (https://www.elastic.co)
13: * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
14: * @license https://www.gnu.org/licenses/lgpl-2.1.html GNU Lesser General Public License, Version 2.1
15: *
16: * Licensed to Elasticsearch B.V under one or more agreements.
17: * Elasticsearch B.V licenses this file to you under the Apache 2.0 License or
18: * the GNU Lesser General Public License, Version 2.1, at your option.
19: * See the LICENSE file in the project root for more information.
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: //PHP < 7.2 Define it as 0 so it does nothing
29: define('JSON_INVALID_UTF8_SUBSTITUTE', 0);
30: }
31:
32: class SmartSerializer implements SerializerInterface
33: {
34: /**
35: * {@inheritdoc}
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: * {@inheritdoc}
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: //Not json, return as string
64: return $data;
65: }
66: } else {
67: //No content headers, assume json
68: return $this->decode($data);
69: }
70: }
71:
72: /**
73: * @param string|null $data
74: *
75: * @return array
76: * @throws JsonErrorException
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: