Passed
Pull Request — master (#7)
by Sandro
03:30
created

Json   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Test Coverage

Coverage 81.82%

Importance

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

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-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 34
    public static function encode($value): string
34
    {
35 34
        $flags = \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES | \JSON_PRESERVE_ZERO_FRACTION;
36
37 34
        $json = \json_encode($value, $flags);
38
39 34
        if ((JSON_ERROR_NONE !== $error = \json_last_error()) || $json === false) {
40
            throw new JsonException(\json_last_error_msg(), $error);
41
        }
42
43 34
        return $json;
44
    }
45
46
    /**
47
     * @param string $json
48
     *
49
     * @param bool $assoc
50
     * @param int $depth
51
     * @return mixed
52
     *
53
     */
54 7
    public static function decode(string $json, bool $assoc = true, int $depth = 512)
55
    {
56 7
        $data = \json_decode($json, $assoc, $depth, \JSON_BIGINT_AS_STRING);
57
58 7
        if (JSON_ERROR_NONE !== $error = \json_last_error()) {
59
            throw new JsonException(\json_last_error_msg(), $error);
60
        }
61
62 7
        return $data;
63
    }
64
}
65