diff --git a/src/Response.php b/src/Response.php index 98304fe8b..494d7b336 100644 --- a/src/Response.php +++ b/src/Response.php @@ -127,4 +127,30 @@ public function throw_for_status($allow_redirects = true) { throw new $exception(null, $this); } } + + /** + * Returns json decoded response + * + * @throws Requests_Exception If `$this->body` is not a valid json + * @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[$last_error]) ? $json_errors[$last_error] : 'Unknown error'; + throw new Requests_Exception('Unable to parse JSON data: ' . $error, 'response.invalid', $this); + } + + return $data; + } } diff --git a/tests/Response.php b/tests/Response.php new file mode 100644 index 000000000..bba8582c8 --- /dev/null +++ b/tests/Response.php @@ -0,0 +1,29 @@ +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]); + } + } +}