Skip to content

Commit 082f738

Browse files
committed
Wrap json_encode() to throw error when the value being encoded fails
1 parent 6226ca0 commit 082f738

File tree

1 file changed

+32
-9
lines changed

1 file changed

+32
-9
lines changed

src/Curl/Curl.php

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -143,15 +143,7 @@ public function buildPostData($data)
143143
// Return JSON-encoded string when the request's content-type is JSON.
144144
if (isset($this->headers['Content-Type']) &&
145145
preg_match($this->jsonPattern, $this->headers['Content-Type'])) {
146-
$data = json_encode($data);
147-
if (!(json_last_error() === JSON_ERROR_NONE)) {
148-
if (function_exists('json_last_error_msg')) {
149-
$error_message = 'json_encode error: ' . json_last_error_msg();
150-
} else {
151-
$error_message = 'json_encode error';
152-
}
153-
throw new \ErrorException($error_message);
154-
}
146+
$data = \Curl\json_encode($data);
155147
} else {
156148
// Manually build a single-dimensional array from a multi-dimensional array as using curl_setopt($ch,
157149
// CURLOPT_POSTFIELDS, $data) doesn't correctly handle multi-dimensional arrays when files are
@@ -1761,3 +1753,34 @@ function createHeaderCallback($header_callback_data) {
17611753
return strlen($header);
17621754
};
17631755
}
1756+
1757+
/**
1758+
* Json Encode
1759+
*
1760+
* Wrap json_encode() to throw error when the value being encoded fails.
1761+
*
1762+
* @param $value
1763+
* @param $options
1764+
* @param $depth
1765+
*
1766+
* @return string
1767+
* @throws \ErrorException
1768+
*/
1769+
function json_encode($value, $options = 0, $depth = 512) {
1770+
// Make compatible with PHP version both before and after 5.5.0. PHP 5.5.0 added the $depth parameter.
1771+
$gte_v550 = version_compare(PHP_VERSION, '5.5.0') >= 0;
1772+
if ($gte_v550) {
1773+
$value = \json_encode($value, $options, $depth);
1774+
} else {
1775+
$value = \json_encode($value, $options);
1776+
}
1777+
if (!(json_last_error() === JSON_ERROR_NONE)) {
1778+
if (function_exists('json_last_error_msg')) {
1779+
$error_message = 'json_encode error: ' . json_last_error_msg();
1780+
} else {
1781+
$error_message = 'json_encode error';
1782+
}
1783+
throw new \ErrorException($error_message);
1784+
}
1785+
return $value;
1786+
}

0 commit comments

Comments
 (0)