JsonHelper::jsonEncode()   A
last analyzed

Complexity

Conditions 6
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 6
eloc 8
c 1
b 0
f 1
nc 3
nop 3
dl 0
loc 15
rs 9.2222
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Solr Client Symfony package.
7
 *
8
 * (c) ingatlan.com Zrt. <[email protected]>
9
 *
10
 * This source file is subject to the MIT license that is bundled
11
 * with this source code in the file LICENSE.
12
 */
13
14
namespace iCom\SolrClient;
15
16
use Symfony\Component\HttpClient\Exception\InvalidArgumentException;
17
18
/**
19
 * @internal
20
 *
21
 * @psalm-immutable
22
 */
23
trait JsonHelper
24
{
25
    /**
26
     * @param mixed $value
27
     *
28
     * @throws InvalidArgumentException when the value cannot be json-encoded
29
     *
30
     * @psalm-pure
31
     */
32
    private static function jsonEncode($value, ?int $flags = null, int $maxDepth = 512): string
33
    {
34
        $flags = $flags ?? (JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_PRESERVE_ZERO_FRACTION);
35
36
        try {
37
            $value = json_encode($value, $flags | (\PHP_VERSION_ID >= 70300 ? \JSON_THROW_ON_ERROR : 0), $maxDepth);
38
        } catch (\JsonException $e) {
39
            throw new InvalidArgumentException(sprintf('Invalid value for "json" option: %s.', $e->getMessage()));
40
        }
41
42
        if (\PHP_VERSION_ID < 70300 && JSON_ERROR_NONE !== json_last_error() && false === $value) {
43
            throw new InvalidArgumentException(sprintf('Invalid value for "json" option: %s.', json_last_error_msg()));
44
        }
45
46
        return $value;
47
    }
48
}
49