-
Notifications
You must be signed in to change notification settings - Fork 0
/
JSON.php
87 lines (80 loc) · 1.85 KB
/
JSON.php
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
namespace moonland\helpers;
/**
* JSON is a encoder and decoder json format to array or array format to json.
* @author Moh Khoirul Anam <[email protected]>
* @copyright 2015
* @since 1
*
*/
class JSON
{
public static function encode($options)
{
//return static::encoder($options);
return static::json_func_expr(json_encode($options));
}
protected static function json_func_expr($json)
{
return preg_replace_callback(
'/(?<=:)"function\((?:(?!}").)*}"/',
'static::json_strip_escape',
$json
);
}
protected static function json_strip_escape($string)
{
return str_replace(
array('\n','\t','\"', '\\\\','\\/'),
array('','','"','\\','/'),
substr($string[0],1,-1)
);
}
public static function encoder($options)
{
if (is_array($options)) {
$text = [];
$countData = count($options);
$data = 1;
foreach ($options as $key=>$value)
{
$keyObject = rand(000000, 999999);
$text[$keyObject] = '';
if ($data == 1) {
if (is_numeric($key)) {
$text[$keyObject] .= '[';
} elseif (is_string($key)) {
$text[$keyObject] .= '{';
}
}
$text[$keyObject] .= static::jsEncoder($key) .':';
if (is_array($value)) {
$text[$keyObject] .= static::encoder($value);
} elseif (is_string($value)) {
$text[$keyObject] .= static::jsEncoder($value);
} elseif (is_numeric($value)) {
$text[$keyObject] .= $value;
}
if ($data == $countData) {
if (is_numeric($key)) {
$text[$keyObject] .= ']';
} elseif (is_string($key)) {
$text[$keyObject] .= '}';
}
}
$data++;
}
$text_result = implode(',', $text);
}
return $text_result;
}
protected static function jsEncoder($key)
{
if (preg_match('/\bjs:/', $key)) {
$key = str_replace('js:','',$key);
return $key;
} else {
return '"'.$key.'"';
}
}
}