Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

parseWith support for any callable method #221

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/Httpful/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -610,22 +610,22 @@ public function withAutoParsing()

/**
* Use a custom function to parse the response.
* @param \Closure $callback Takes the raw body of
* @param Callable $callback Takes the raw body of
* the http response and returns a mixed
* @return Request
*/
public function parseWith(\Closure $callback)
public function parseWith(Callable $callback)
{
$this->parse_callback = $callback;
return $this;
}

/**
* @see Request::parseResponsesWith()
* @param \Closure $callback
* @param Callable $callback
* @return Request
*/
public function parseResponsesWith(\Closure $callback)
public function parseResponsesWith(Callable $callback)
{
return $this->parseWith($callback);
}
Expand Down
26 changes: 26 additions & 0 deletions tests/Httpful/HttpfulTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,32 @@ function testJsonResponseParse()
$this->assertEquals(1, $response->body->array[0]);
}

function testResponseParseWithInline()
{
$req = Request::init()->sendsAndExpects(Mime::JSON)
->parseWith(function($body) {
return json_decode($body);
});
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);

$this->assertEquals("value", $response->body->key);
$this->assertEquals("value", $response->body->object->key);
$this->assertInternalType('array', $response->body->array);
$this->assertEquals(1, $response->body->array[0]);
}

function testResponseParseWithCallable()
{
$req = Request::init()->sendsAndExpects(Mime::JSON)
->parseWith("json_decode");
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);

$this->assertEquals("value", $response->body->key);
$this->assertEquals("value", $response->body->object->key);
$this->assertInternalType('array', $response->body->array);
$this->assertEquals(1, $response->body->array[0]);
}

function testXMLResponseParse()
{
$req = Request::init()->sendsAndExpects(Mime::XML);
Expand Down