PluginProbe
Packeta / trunk
Packeta vtrunk
2.3.2 2.3.1 trunk 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.3.0 1.3.1 1.3.2 1.4 1.4.1 1.4.2 1.4.3 1.5.0 1.5.1 1.5.2 1.5.3 1.5.4 1.6.0 1.6.1 1.6.2 1.6.3 1.6.4 All 56 releases
packeta / deps / nette / utils / src / Utils / Json.php

Json.php in Packeta trunk, at deps/nette/utils/src/Utils/Json.php

50 lines 1.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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 declare (strict_types=1);
8 namespace Packetery\Nette\Utils;
9
10 use Packetery\Nette;
11 /**
12 * JSON encoder and decoder.
13 */
14 final class Json
15 {
16 use \Packetery\Nette\StaticClass;
17 public const FORCE_ARRAY = \JSON_OBJECT_AS_ARRAY;
18 public const PRETTY = \JSON_PRETTY_PRINT;
19 public const ESCAPE_UNICODE = 1 << 19;
20 /**
21 * Converts value to JSON format. The flag can be Json::PRETTY, which formats JSON for easier reading and clarity,
22 * and Json::ESCAPE_UNICODE for ASCII output.
23 * @param mixed $value
24 * @throws JsonException
25 */
26 public static function encode($value, int $flags = 0) : string
27 {
28 $flags = ($flags & self::ESCAPE_UNICODE ? 0 : \JSON_UNESCAPED_UNICODE) | \JSON_UNESCAPED_SLASHES | $flags & ~self::ESCAPE_UNICODE | (\defined('JSON_PRESERVE_ZERO_FRACTION') ? \JSON_PRESERVE_ZERO_FRACTION : 0);
29 // since PHP 5.6.6 & PECL JSON-C 1.3.7
30 $json = \json_encode($value, $flags);
31 if ($error = \json_last_error()) {
32 throw new JsonException(\json_last_error_msg(), $error);
33 }
34 return $json;
35 }
36 /**
37 * Parses JSON to PHP value. The flag can be Json::FORCE_ARRAY, which forces an array instead of an object as the return value.
38 * @return mixed
39 * @throws JsonException
40 */
41 public static function decode(string $json, int $flags = 0)
42 {
43 $value = \json_decode($json, null, 512, $flags | \JSON_BIGINT_AS_STRING);
44 if ($error = \json_last_error()) {
45 throw new JsonException(\json_last_error_msg(), $error);
46 }
47 return $value;
48 }
49 }
50