From 082f7389e31e4125a94e3f3eb9eed42532ebfa91 Mon Sep 17 00:00:00 2001 From: Zach Borboa Date: Wed, 1 Aug 2018 23:45:57 -0700 Subject: [PATCH] Wrap json_encode() to throw error when the value being encoded fails --- src/Curl/Curl.php | 41 ++++++++++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/src/Curl/Curl.php b/src/Curl/Curl.php index 0a438fb..45024c3 100644 --- a/src/Curl/Curl.php +++ b/src/Curl/Curl.php @@ -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; +}