Skip to content

Commit d9081ff

Browse files
committed
Check Json types
1 parent 6a45a21 commit d9081ff

File tree

1 file changed

+26
-6
lines changed

1 file changed

+26
-6
lines changed

src/Common/Common.php

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,25 +21,45 @@ public static function mysql_escape($fieldValue)
2121
}
2222

2323
if(self::is_json($fieldValue)){
24-
return $fieldValue;
24+
return self::safeString($fieldValue);
2525
}
2626

2727
if (!empty($fieldValue) && is_string($fieldValue)) {
28-
return str_replace(
29-
['\\', "\0", "\n", "\r", "'", '"', "\x1a"],
30-
['\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'],
31-
$fieldValue
32-
);
28+
return self::safeJson($fieldValue);
3329
}
3430

3531
return $fieldValue;
3632
}
3733

34+
protected static function safeString($fieldValue){
35+
return str_replace(
36+
['\\', "\0", "\n", "\r", "'", '"', "\x1a"],
37+
['\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'],
38+
$fieldValue
39+
);
40+
}
41+
3842
protected static function is_json($str): bool
3943
{
4044
if (!is_string($str)){
4145
return false;
4246
}
4347
return json_decode($str, true) !== null;
4448
}
49+
50+
protected static function safeJson($jsonData,$asArray = false){
51+
$jsonData = json_decode($jsonData,true);
52+
$safeJsonData = [];
53+
foreach ($jsonData as $key => $value){
54+
if (self::is_json($value)){
55+
$safeJsonData[$key] = self::safeJson($jsonData,true);
56+
}elseif(is_string($value)){
57+
$safeJsonData[$key] = self::safeString($value);
58+
}else{
59+
$safeJsonData[$key] = $value;
60+
}
61+
}
62+
return $asArray ? $safeJsonData : json_encode($safeJsonData);
63+
}
64+
4565
}

0 commit comments

Comments
 (0)