Add json encoding when request header Content-Type is set to application/json

This commit is contained in:
Zach Borboa
2014-12-31 01:14:18 -08:00
parent 5d7d25ac15
commit 80adf0f3a1
3 changed files with 48 additions and 3 deletions
+14 -3
View File
@@ -17,6 +17,9 @@ class Curl
private $error_function = null;
private $complete_function = null;
private $json_pattern = '~^application/(?:json|vnd\.api\+json)~i';
private $xml_pattern = '~^(?:text/|application/(?:atom\+|rss\+)?)xml~i';
public $curl;
public $curls;
@@ -369,12 +372,12 @@ class Curl
$response = $raw_response;
if (isset($response_headers['Content-Type'])) {
if (preg_match('~^application/(?:json|vnd\.api\+json)~i', $response_headers['Content-Type'])) {
if (preg_match($this->json_pattern, $response_headers['Content-Type'])) {
$json_obj = json_decode($response, false);
if ($json_obj !== null) {
$response = $json_obj;
}
} elseif (preg_match('~^(?:text/|application/(?:atom\+|rss\+)?)xml~i', $response_headers['Content-Type'])) {
} elseif (preg_match($this->xml_pattern, $response_headers['Content-Type'])) {
$xml_obj = @simplexml_load_string($response);
if (!($xml_obj === false)) {
$response = $xml_obj;
@@ -432,7 +435,15 @@ class Curl
}
if (!$binary_data) {
$data = http_build_query($data);
if (isset($this->headers['Content-Type']) &&
preg_match($this->json_pattern, $this->headers['Content-Type'])) {
$json_str = json_encode($data);
if (!($json_str === false)) {
$data = $json_str;
}
} else {
$data = http_build_query($data);
}
}
}
}
+31
View File
@@ -649,6 +649,37 @@ class CurlTest extends PHPUnit_Framework_TestCase
$this->assertFalse(file_exists($file_path));
}
public function testJSONRequest()
{
$data = array('key' => 'value');
$expected_response = '{"key":"value"}';
$test = new Test();
$this->assertEquals($expected_response, $test->server('post_json', 'POST', json_encode($data)));
foreach (array(
'Content-Type',
'content-type',
'CONTENT-TYPE') as $key) {
foreach (array(
'APPLICATION/JSON',
'APPLICATION/JSON; CHARSET=UTF-8',
'APPLICATION/JSON;CHARSET=UTF-8',
'application/json',
'application/json; charset=utf-8',
'application/json;charset=UTF-8',
) as $value) {
$test = new Test();
$test->curl->setHeader($key, $value);
$this->assertEquals($expected_response, $test->server('post_json', 'POST', json_encode($data)));
$test = new Test();
$test->curl->setHeader($key, $value);
$this->assertEquals($expected_response, $test->server('post_json', 'POST', $data));
}
}
}
public function testJSONResponse()
{
function assertion($key, $value)
+3
View File
@@ -50,6 +50,9 @@ if ($test == 'http_basic_auth') {
} elseif ($test === 'post') {
echo http_build_query($_POST);
exit;
} elseif ($test === 'post_json') {
echo $http_raw_post_data;
exit;
} elseif ($test === 'put') {
echo $http_raw_post_data;
exit;