Skip to content

Commit

Permalink
Closes #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 body is a valid json else throws an exception
  • Loading branch information
ccrims0n authored and jrfnl committed Sep 18, 2021
1 parent f93bf6b commit bdd5821
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
29 changes: 29 additions & 0 deletions tests/Response.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?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]);
}
}
}

0 comments on commit bdd5821

Please sign in to comment.