Completed
Pull Request — master (#7)
by Sandro
03:08
created

Json   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 81.82%

Importance

Changes 0
Metric Value
wmc 5
eloc 10
dl 0
loc 38
ccs 9
cts 11
cp 0.8182
rs 10
c 0
b 0
f 0

2 Methods

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