|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Util |
|
4
|
|
|
* |
|
5
|
|
|
* @copyright Copyright (c) Gjero Krsteski (http://krsteski.de) |
|
6
|
|
|
* @license http://opensource.org/licenses/MIT MIT License |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace Pimf\Util; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* @package Util |
|
13
|
|
|
* @author Gjero Krsteski <[email protected]> |
|
14
|
|
|
*/ |
|
15
|
|
|
class Json |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* Returns the JSON representation of a value. |
|
19
|
|
|
* |
|
20
|
|
|
* @param mixed $data |
|
21
|
|
|
* |
|
22
|
|
|
* @return string |
|
23
|
|
|
*/ |
|
24
|
|
|
public static function encode($data) |
|
25
|
|
|
{ |
|
26
|
|
|
if (version_compare(PHP_VERSION, '5.4.0', '>=')) { |
|
27
|
|
|
$json = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); |
|
28
|
|
|
} else { |
|
29
|
|
|
$json = json_encode($data); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
self::handleError(json_last_error()); |
|
33
|
|
|
|
|
34
|
|
|
return $json; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* Decodes a JSON string. |
|
39
|
|
|
* |
|
40
|
|
|
* @param string $jsonString |
|
41
|
|
|
* @param boolean $assoc If should be converted into associative array/s. |
|
42
|
|
|
* |
|
43
|
|
|
* @return mixed |
|
44
|
|
|
*/ |
|
45
|
|
|
public static function decode($jsonString, $assoc = false) |
|
46
|
|
|
{ |
|
47
|
|
|
$json = json_decode($jsonString, $assoc); |
|
48
|
|
|
|
|
49
|
|
|
self::handleError(json_last_error()); |
|
50
|
|
|
|
|
51
|
|
|
return $json; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
/** |
|
55
|
|
|
* @param int $status |
|
56
|
|
|
* |
|
57
|
|
|
* @throws \RuntimeException |
|
58
|
|
|
*/ |
|
59
|
|
|
protected static function handleError($status) |
|
60
|
|
|
{ |
|
61
|
|
|
$msg = ''; |
|
62
|
|
|
|
|
63
|
|
|
switch ($status) { |
|
64
|
|
|
case JSON_ERROR_DEPTH: |
|
65
|
|
|
$msg = 'Maximum stack depth exceeded'; |
|
66
|
|
|
break; |
|
67
|
|
|
case JSON_ERROR_STATE_MISMATCH: |
|
68
|
|
|
$msg = 'Underflow or the modes mismatch'; |
|
69
|
|
|
break; |
|
70
|
|
|
case JSON_ERROR_CTRL_CHAR: |
|
71
|
|
|
$msg = 'Unexpected control character found'; |
|
72
|
|
|
break; |
|
73
|
|
|
case JSON_ERROR_SYNTAX: |
|
74
|
|
|
$msg = 'Syntax error, malformed JSON'; |
|
75
|
|
|
break; |
|
76
|
|
|
case 5: //alias for JSON_ERROR_UTF8 due to Availability PHP 5.3.3 |
|
77
|
|
|
$msg = 'Malformed UTF-8 characters, possibly incorrectly encoded'; |
|
78
|
|
|
break; |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
|
|
if ($msg !== '') { |
|
82
|
|
|
throw new \RuntimeException($msg); |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
|