-
-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathJson.php
More file actions
66 lines (51 loc) · 1.53 KB
/
Json.php
File metadata and controls
66 lines (51 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Utils;
use Nette;
/**
* JSON encoder and decoder.
*/
final class Json
{
use Nette\StaticClass;
public const FORCE_ARRAY = 0b0001;
public const PRETTY = 0b0010;
public const ESCAPE_UNICODE = 0b0100;
const FORCE_OBJECT = 0b10000;
/**
* Returns the JSON representation of a value. Accepts flag Json::PRETTY and JSON::FORCE_OBJECT.
* @param mixed $value
* @throws JsonException
*/
public static function encode($value, int $flags = 0): string
{
$flags = ($flags & self::ESCAPE_UNICODE ? 0 : JSON_UNESCAPED_UNICODE)
| JSON_UNESCAPED_SLASHES
| ($flags & self::PRETTY ? JSON_PRETTY_PRINT : 0)
| ($flags & self::FORCE_OBJECT ? JSON_FORCE_OBJECT : 0)
| (defined('JSON_PRESERVE_ZERO_FRACTION') ? JSON_PRESERVE_ZERO_FRACTION : 0); // since PHP 5.6.6 & PECL JSON-C 1.3.7
$json = json_encode($value, $flags);
if ($error = json_last_error()) {
throw new JsonException(json_last_error_msg(), $error);
}
return $json;
}
/**
* Decodes a JSON string. Accepts flag Json::FORCE_ARRAY.
* @return mixed
* @throws JsonException
*/
public static function decode(string $json, int $flags = 0)
{
$forceArray = (bool) ($flags & self::FORCE_ARRAY);
$value = json_decode($json, $forceArray, 512, JSON_BIGINT_AS_STRING);
if ($error = json_last_error()) {
throw new JsonException(json_last_error_msg(), $error);
}
return $value;
}
}