Last active
December 23, 2015 08:49
-
-
Save rybakit/6610129 to your computer and use it in GitHub Desktop.
Json listener for Buzz http client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Buzz\Listener\ListenerInterface; | |
use Buzz\Message\MessageInterface; | |
use Buzz\Message\RequestInterface; | |
class JsonListener implements ListenerInterface | |
{ | |
/** | |
* {@inheritdoc} | |
*/ | |
public function preSend(RequestInterface $request) | |
{ | |
$request->addHeader('Accept: application/json'); | |
$request->setContent(json_encode($request->getContent())); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function postSend(RequestInterface $request, MessageInterface $response) | |
{ | |
$content = json_decode($response->getContent(), true); | |
if (JSON_ERROR_NONE !== json_last_error()) { | |
throw new \RuntimeException('Invalid JSON.'); | |
} | |
$response->setContent(is_array($content) ? $content : array()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment