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