Skip to content

Commit

Permalink
Closes WordPress#167 - Add json() for json responses
Browse files Browse the repository at this point in the history
* Add json() which returns decoded json from the response body
  if the response bosy is a valid json else throws an exception
  • Loading branch information
ccrims0n committed Jun 3, 2016
1 parent a71ab70 commit 00c0271
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
28 changes: 28 additions & 0 deletions library/Requests/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,32 @@ public function throw_for_status($allow_redirects = true) {
throw new $exception(null, $this);
}
}

/**
* Returns json decoded response
*
* @throws
* @return array
*/
public function json($assoc = true, $depth = 512, $options = 0) {
static $json_errors = array(
JSON_ERROR_DEPTH => 'JSON_ERROR_DEPTH - Maximum stack depth exceeded',
JSON_ERROR_STATE_MISMATCH => 'JSON_ERROR_STATE_MISMATCH - Underflow or the modes mismatch',
JSON_ERROR_CTRL_CHAR => 'JSON_ERROR_CTRL_CHAR - Unexpected control character found',
JSON_ERROR_SYNTAX => 'JSON_ERROR_SYNTAX - Syntax error, malformed JSON',
JSON_ERROR_UTF8 => 'JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded'
);

$data = json_decode($this->body, $assoc, $depth, $options);

if (JSON_ERROR_NONE !== json_last_error()) {
$last_error = json_last_error();

$error = isset($json_errors) ? $json_errors[$last_error] : 'Unknown error';

throw new Requests_Exception('Unable to parse JSON data: ' . $error, 'response.invalid', $this);
}

return $data;
}
}
33 changes: 33 additions & 0 deletions tests/Response.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

class RequestsTest_Response extends PHPUnit_Framework_TestCase {
/**
* @expectedException Requests_Exception
*/
public function testInvalidJsonResponse() {
$response = new Requests_Response();

$response->body = 'Invalid JSON';

$response->json();
}

public function testJsonResponse() {
$response = new Requests_Response();

$response->body = '{"success": false, "error": [], "data": null}';

$decodedBody = $response->json();

$expected = array(
'success' => false,
'error' => array(),
'data' => null
);

foreach($expected as $key => $value)
{
$this->assertEquals($value, $decodedBody[$key]);
}
}
}
1 change: 1 addition & 0 deletions tests/phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<file>IDNAEncoder.php</file>
<file>IRI.php</file>
<file>Requests.php</file>
<file>Response.php</file>
<file>Response/Headers.php</file>
<file>Session.php</file>
<file>SSL.php</file>
Expand Down

0 comments on commit 00c0271

Please sign in to comment.