Skip to content

Instantly share code, notes, and snippets.

@rybakit
Last active December 23, 2015 08:49
Show Gist options
  • Save rybakit/6610129 to your computer and use it in GitHub Desktop.
Save rybakit/6610129 to your computer and use it in GitHub Desktop.
Json listener for Buzz http client
<?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