friendship ended with social-app. php is my new best friend
1<?php
2
3/**
4 * This file is part of the Nette Framework (https://nette.org)
5 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6 */
7
8declare(strict_types=1);
9
10namespace Nette\Utils;
11
12use Nette;
13use function defined, is_int, json_decode, json_encode, json_last_error, json_last_error_msg;
14use const JSON_BIGINT_AS_STRING, JSON_FORCE_OBJECT, JSON_HEX_AMP, JSON_HEX_APOS, JSON_HEX_QUOT, JSON_HEX_TAG, JSON_OBJECT_AS_ARRAY, JSON_PRESERVE_ZERO_FRACTION, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE;
15
16
17/**
18 * JSON encoder and decoder.
19 */
20final class Json
21{
22 use Nette\StaticClass;
23
24 /** @deprecated use Json::decode(..., forceArrays: true) */
25 public const FORCE_ARRAY = JSON_OBJECT_AS_ARRAY;
26
27 /** @deprecated use Json::encode(..., pretty: true) */
28 public const PRETTY = JSON_PRETTY_PRINT;
29
30 /** @deprecated use Json::encode(..., asciiSafe: true) */
31 public const ESCAPE_UNICODE = 1 << 19;
32
33
34 /**
35 * Converts value to JSON format. Use $pretty for easier reading and clarity, $asciiSafe for ASCII output
36 * and $htmlSafe for HTML escaping, $forceObjects enforces the encoding of non-associateve arrays as objects.
37 * @throws JsonException
38 */
39 public static function encode(
40 mixed $value,
41 bool|int $pretty = false,
42 bool $asciiSafe = false,
43 bool $htmlSafe = false,
44 bool $forceObjects = false,
45 ): string
46 {
47 if (is_int($pretty)) { // back compatibility
48 $flags = ($pretty & self::ESCAPE_UNICODE ? 0 : JSON_UNESCAPED_UNICODE) | ($pretty & ~self::ESCAPE_UNICODE);
49 } else {
50 $flags = ($asciiSafe ? 0 : JSON_UNESCAPED_UNICODE)
51 | ($pretty ? JSON_PRETTY_PRINT : 0)
52 | ($forceObjects ? JSON_FORCE_OBJECT : 0)
53 | ($htmlSafe ? JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_TAG : 0);
54 }
55
56 $flags |= JSON_UNESCAPED_SLASHES
57 | (defined('JSON_PRESERVE_ZERO_FRACTION') ? JSON_PRESERVE_ZERO_FRACTION : 0); // since PHP 5.6.6 & PECL JSON-C 1.3.7
58
59 $json = json_encode($value, $flags);
60 if ($error = json_last_error()) {
61 throw new JsonException(json_last_error_msg(), $error);
62 }
63
64 return $json;
65 }
66
67
68 /**
69 * Parses JSON to PHP value. The $forceArrays enforces the decoding of objects as arrays.
70 * @throws JsonException
71 */
72 public static function decode(string $json, bool|int $forceArrays = false): mixed
73 {
74 $flags = is_int($forceArrays) // back compatibility
75 ? $forceArrays
76 : ($forceArrays ? JSON_OBJECT_AS_ARRAY : 0);
77 $flags |= JSON_BIGINT_AS_STRING;
78
79 $value = json_decode($json, flags: $flags);
80 if ($error = json_last_error()) {
81 throw new JsonException(json_last_error_msg(), $error);
82 }
83
84 return $value;
85 }
86}