Merge pull request #533 from zachborboa/master

Throw error when json_encode fails
This commit is contained in:
Zach Borboa
2018-07-27 23:29:11 -07:00
committed by GitHub
2 changed files with 23 additions and 3 deletions
+9 -3
View File
@@ -134,6 +134,7 @@ class Curl
* @param $data
*
* @return array|string
* @throws \ErrorException
*/
public function buildPostData($data)
{
@@ -142,9 +143,14 @@ 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'])) {
$json_str = json_encode($data);
if (!($json_str === false)) {
$data = $json_str;
$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);
}
} else {
// Manually build a single-dimensional array from a multi-dimensional array as using curl_setopt($ch,
+14
View File
@@ -1381,6 +1381,20 @@ class CurlTest extends \PHPUnit\Framework\TestCase
}
}
/**
* @expectedException \ErrorException
*/
public function testJsonEncode()
{
$data = array(
'malformed' => pack('H*', 'c32e'),
);
$test = new Test();
$test->curl->setHeader('Content-Type', 'application/json');
$test->server('post_json', 'POST', $data);
}
public function testJsonDecoderOptions()
{
// Implicit default json decoder should return object.