1<?php
2
3declare(strict_types = 1);
4
5namespace Elasticsearch\Serializers;
6
7use Elasticsearch\Common\Exceptions\RuntimeException;
8
9if (!defined('JSON_INVALID_UTF8_SUBSTITUTE')) {
10    //PHP < 7.2 Define it as 0 so it does nothing
11    define('JSON_INVALID_UTF8_SUBSTITUTE', 0);
12}
13
14/**
15 * Class EverythingToJSONSerializer
16 *
17 * @category Elasticsearch
18 * @package  Elasticsearch\Serializers
19 * @author   Zachary Tong <zach@elastic.co>
20 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache2
21 * @link     http://elastic.co
22 */
23class EverythingToJSONSerializer implements SerializerInterface
24{
25    /**
26     * {@inheritdoc}
27     */
28    public function serialize($data): string
29    {
30        $data = json_encode($data, JSON_PRESERVE_ZERO_FRACTION + JSON_INVALID_UTF8_SUBSTITUTE);
31        if ($data === false) {
32            throw new RuntimeException("Failed to JSON encode: ".json_last_error());
33        }
34        if ($data === '[]') {
35            return '{}';
36        } else {
37            return $data;
38        }
39    }
40
41    /**
42     * {@inheritdoc}
43     */
44    public function deserialize(?string $data, array $headers)
45    {
46        return json_decode($data, true);
47    }
48}
49