Completed
Pull Request — master (#7)
by Sandro
02:21
created

Json::decode()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 9
ccs 4
cts 5
cp 0.8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2.032
1
<?php
2
/**
3
 * Sandro Keil (https://sandro-keil.de)
4
 *
5
 * @link      http://github.com/sandrokeil/arangodb-php-client for the canonical source repository
6
 * @copyright Copyright (c) 2018-2019 Sandro Keil
7
 * @license   http://github.com/sandrokeil/arangodb-php-client/blob/master/LICENSE.md New BSD License
8
 */
9
declare(strict_types=1);
10
11
namespace ArangoDb\Util;
12
13
use ArangoDb\Exception\JsonException;
14
15
/**
16
 * Code is largely lifted from the Prooph\EventStore\Pdo\Util\Json implementation in
17
 * prooph/pdo-event-store, released with the copyright and license below.
18
 *
19
 * @see       https://github.com/prooph/pdo-event-store for the canonical source repository
20
 * @copyright Copyright (c) 2016-2019 prooph software GmbH <[email protected]>
21
 * @copyright Copyright (c) 2016-2019 Sascha-Oliver Prolic <[email protected]>
22
 * @license   https://github.com/prooph/pdo-event-store/blob/master/LICENSE New BSD License
23
 */
24
class Json
25
{
26
    /**
27
     * @param mixed $value
28
     *
29
     * @return string
30
     *
31
     * @throws JsonException
32
     */
33 35
    public static function encode($value): string
34
    {
35 35
        $flags = \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES | \JSON_PRESERVE_ZERO_FRACTION;
36
37 35
        $json = \json_encode($value, $flags);
38
39 35
        if ((JSON_ERROR_NONE !== $error = \json_last_error()) || $json === false) {
40
            throw new JsonException(\json_last_error_msg(), $error);
41
        }
42
43 35
        return $json;
44
    }
45
46
    /**
47
     * @param string $json
48
     *
49
     * @return mixed
50
     *
51
     * @throws JsonException
52
     */
53 15
    public static function decode(string $json)
54
    {
55 15
        $data = \json_decode($json, true, 512, \JSON_BIGINT_AS_STRING);
56
57 15
        if (JSON_ERROR_NONE !== $error = \json_last_error()) {
58
            throw new JsonException(\json_last_error_msg(), $error);
59
        }
60
61 15
        return $data;
62
    }
63
}
64