Merge pull request #544 from zachborboa/master

Fix xml response when xml decode fails
This commit is contained in:
Zach Borboa
2018-08-23 23:55:33 -07:00
committed by GitHub
3 changed files with 46 additions and 35 deletions
+1 -32
View File
@@ -151,7 +151,7 @@ class Curl
$data instanceof \JsonSerializable
)
)) {
$data = \Curl\json_encode($data);
$data = \Curl\Encoder::encodeJson($data);
} elseif (is_array($data)) {
// 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
@@ -1760,34 +1760,3 @@ 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;
}
+3 -3
View File
@@ -44,9 +44,9 @@ class Decoder
public static function decodeXml()
{
$args = func_get_args();
$xml_obj = @call_user_func_array('simplexml_load_string', $args);
if (!($xml_obj === false)) {
$response = $xml_obj;
$response = @call_user_func_array('simplexml_load_string', $args);
if ($response === false) {
$response = $args['0'];
}
return $response;
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace Curl;
class Encoder
{
/**
* Encode JSON
*
* Wrap json_encode() to throw error when the value being encoded fails.
*
* @access public
* @param $value
* @param $options
* @param $depth
*
* @return string
* @throws \ErrorException
*/
public static function encodeJson()
{
$args = func_get_args();
// Call json_encode() without the $depth parameter in PHP
// versions less than 5.5.0 as the $depth parameter was added in
// PHP version 5.5.0.
if (version_compare(PHP_VERSION, '5.5.0', '<')) {
$args = array_slice($args, 0, 2);
}
$value = call_user_func_array('json_encode', $args);
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;
}
}