forked from sinacms/MultiHttp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJson.php
More file actions
executable file
·71 lines (65 loc) · 1.84 KB
/
Json.php
File metadata and controls
executable file
·71 lines (65 loc) · 1.84 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
67
68
69
70
<?php
/**
*
* @author qiangjian@staff.sina.com.cn sunsky303@gmail.com
* Date: 2017/6/16
* Time: 10:02
* @version $Id: $
* @since 1.0
* @copyright Sina Corp.
*/
namespace MultiHttp\Handler;
use MultiHttp\Exception\UnexpectedResponseException;
/**
* @package MultiHttp
*/
class Json implements IHandler
{
/**
* @param $body
* @return string
*/
public function encode($body)
{
return json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
/**
* @param $body
* @return mixed
*/
public function decode($body)
{
$parsed = json_decode($body, true);
if(json_last_error() !== JSON_ERROR_NONE)throw new UnexpectedResponseException('parsing json occurs error: '. self::jsonLastErrorMsg() . ', raw body: ' .$body );
return $parsed;
}
/**
* @return string
*/
private static function jsonLastErrorMsg(){
if(function_exists('json_last_error_msg')) return json_last_error_msg();
switch (json_last_error()) {
case JSON_ERROR_NONE:
return ' - No errors';
break;
case JSON_ERROR_DEPTH:
return ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
return ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
return ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
return ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
return ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
return ' - Unknown error';
break;
}
}
}