-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHelpers.php
More file actions
72 lines (65 loc) · 2.22 KB
/
Helpers.php
File metadata and controls
72 lines (65 loc) · 2.22 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
71
72
<?php
namespace Matscode\Paystack\Utility;
use Matscode\Paystack\Exceptions\JsonException;
final class Helpers
{
/**
* Parse response PSR7 stream to Obj
*
* @param $jsonString
* @return \StdClass
* @throws JsonException
*/
public static function JSONStringToObj($jsonString): \StdClass
{
return self::parseJSON((string)$jsonString);
}
/**
* Parse JSON string to Object
*
* @param string $string Valid JSON string to parse
* @param bool $asObject Parses JSON string as StdClass Object by default, set to false if you want to parse as associate array
*
* @throws JsonException
*/
public static function parseJSON(string $string, bool $asObject = true): \stdClass
{
if (!$string) {
return json_decode('{}', !$asObject, 4);
}
// limit json string parse depth
$decodedJson = json_decode($string, !$asObject, 16);
// see if json parsed successfully
$jsonErrorCode = json_last_error();
if ($jsonErrorCode) {
$exceptionMessage = '';
switch ($jsonErrorCode) {
/*
case JSON_ERROR_NONE:
$exceptionMessage = 'No errors';
break;
*/
case JSON_ERROR_DEPTH:
$exceptionMessage = 'Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
$exceptionMessage = 'Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
$exceptionMessage = 'Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
$exceptionMessage = 'Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
$exceptionMessage = 'Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
$exceptionMessage = 'Unknown error';
break;
}
throw new JsonException($exceptionMessage);
}
return $decodedJson;
}
}