Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.91% covered (success)
90.91%
10 / 11
66.67% covered (warning)
66.67%
2 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
Json
90.91% covered (success)
90.91%
10 / 11
66.67% covered (warning)
66.67%
2 / 3
7.04
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 decodeObject
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 encode
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3declare(strict_types=1);
4
5namespace LambdaTwelve\OneRecord\JsonLd;
6
7use JsonException;
8
9/**
10 * JSON decoding and encoding with the settings every ONE Record body needs:
11 * objects as associative arrays, big integers kept exact, UTF-8 and slashes
12 * left readable on output, and a depth bound so a hostile body cannot
13 * exhaust the stack.
14 */
15final class Json
16{
17    public const int MAX_DEPTH = 64;
18
19    private function __construct() {}
20
21    /**
22     * @return array<string, mixed>
23     */
24    public static function decodeObject(string $json): array
25    {
26        try {
27            $decoded = json_decode($json, true, self::MAX_DEPTH, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
28        } catch (JsonException $e) {
29            throw JsonLdException::invalidJson($e->getMessage());
30        }
31        if (!\is_array($decoded) || array_is_list($decoded)) {
32            throw JsonLdException::at('', 'A JSON-LD document must be a single JSON object');
33        }
34
35        /** @var array<string, mixed> $decoded */
36        return $decoded;
37    }
38
39    /**
40     * @param array<string, mixed> $document
41     */
42    public static function encode(array $document, bool $pretty = true): string
43    {
44        $flags = JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION;
45        if ($pretty) {
46            $flags |= JSON_PRETTY_PRINT;
47        }
48
49        return json_encode($document, $flags, self::MAX_DEPTH);
50    }
51}