mirror of
https://github.com/php-curl-class/php-curl-class.git
synced 2026-08-30 12:14:36 +00:00
Wrap json_encode() to throw error when the value being encoded fails
This commit is contained in:
+32
-9
@@ -143,15 +143,7 @@ class Curl
|
||||
// Return JSON-encoded string when the request's content-type is JSON.
|
||||
if (isset($this->headers['Content-Type']) &&
|
||||
preg_match($this->jsonPattern, $this->headers['Content-Type'])) {
|
||||
$data = json_encode($data);
|
||||
if (!(json_last_error() === JSON_ERROR_NONE)) {
|
||||
if (function_exists('json_last_error_msg')) {
|
||||
$error_message = 'json_encode error: ' . json_last_error_msg();
|
||||
} else {
|
||||
$error_message = 'json_encode error';
|
||||
}
|
||||
throw new \ErrorException($error_message);
|
||||
}
|
||||
$data = \Curl\json_encode($data);
|
||||
} else {
|
||||
// Manually build a single-dimensional array from a multi-dimensional array as using curl_setopt($ch,
|
||||
// CURLOPT_POSTFIELDS, $data) doesn't correctly handle multi-dimensional arrays when files are
|
||||
@@ -1761,3 +1753,34 @@ function createHeaderCallback($header_callback_data) {
|
||||
return strlen($header);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Json Encode
|
||||
*
|
||||
* Wrap json_encode() to throw error when the value being encoded fails.
|
||||
*
|
||||
* @param $value
|
||||
* @param $options
|
||||
* @param $depth
|
||||
*
|
||||
* @return string
|
||||
* @throws \ErrorException
|
||||
*/
|
||||
function json_encode($value, $options = 0, $depth = 512) {
|
||||
// Make compatible with PHP version both before and after 5.5.0. PHP 5.5.0 added the $depth parameter.
|
||||
$gte_v550 = version_compare(PHP_VERSION, '5.5.0') >= 0;
|
||||
if ($gte_v550) {
|
||||
$value = \json_encode($value, $options, $depth);
|
||||
} else {
|
||||
$value = \json_encode($value, $options);
|
||||
}
|
||||
if (!(json_last_error() === JSON_ERROR_NONE)) {
|
||||
if (function_exists('json_last_error_msg')) {
|
||||
$error_message = 'json_encode error: ' . json_last_error_msg();
|
||||
} else {
|
||||
$error_message = 'json_encode error';
|
||||
}
|
||||
throw new \ErrorException($error_message);
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user