1<?php 2/** 3 * Elasticsearch PHP client 4 * 5 * @link https://github.com/elastic/elasticsearch-php/ 6 * @copyright Copyright (c) Elasticsearch B.V (https://www.elastic.co) 7 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0 8 * @license https://www.gnu.org/licenses/lgpl-2.1.html GNU Lesser General Public License, Version 2.1 9 * 10 * Licensed to Elasticsearch B.V under one or more agreements. 11 * Elasticsearch B.V licenses this file to you under the Apache 2.0 License or 12 * the GNU Lesser General Public License, Version 2.1, at your option. 13 * See the LICENSE file in the project root for more information. 14 */ 15 16 17declare(strict_types = 1); 18 19namespace Elasticsearch\Serializers; 20 21use Elasticsearch\Common\Exceptions\RuntimeException; 22 23if (!defined('JSON_INVALID_UTF8_SUBSTITUTE')) { 24 //PHP < 7.2 Define it as 0 so it does nothing 25 define('JSON_INVALID_UTF8_SUBSTITUTE', 0); 26} 27 28class ArrayToJSONSerializer implements SerializerInterface 29{ 30 /** 31 * {@inheritdoc} 32 */ 33 public function serialize($data): string 34 { 35 if (is_string($data) === true) { 36 return $data; 37 } else { 38 $data = json_encode($data, JSON_PRESERVE_ZERO_FRACTION + JSON_INVALID_UTF8_SUBSTITUTE); 39 if ($data === false) { 40 throw new RuntimeException("Failed to JSON encode: ".json_last_error()); 41 } 42 if ($data === '[]') { 43 return '{}'; 44 } else { 45 return $data; 46 } 47 } 48 } 49 50 /** 51 * {@inheritdoc} 52 */ 53 public function deserialize(?string $data, array $headers) 54 { 55 return json_decode($data, true); 56 } 57} 58