Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created September 20, 2022 11:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kobus1998/9d960f63cec72e457b8e368810d4fd42 to your computer and use it in GitHub Desktop.
Save kobus1998/9d960f63cec72e457b8e368810d4fd42 to your computer and use it in GitHub Desktop.
middleware class for guzzlehttp
<?php
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Client;
class History
{
private $int = 0;
private $history = [];
public function getHistory()
{
return $this->history;
}
private function increment()
{
$this->int++;
}
private function saveResponse(ResponseInterface $response)
{
$this->history[$this->int]['response'] = (clone $response);
$this->increment();
}
private function saveRequest(RequestInterface $request)
{
$this->history[$this->int]['request'] = (clone $request);
}
public function __invoke(callable $handler)
{
return function (RequestInterface $request, array $options) use ($handler) {
// save request
$this->saveRequest($request);
// save response
return $handler($request, $options)->then(function (ResponseInterface $response) {
$this->saveResponse($response);
});
};
}
}
$history = new History;
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push($history);
$client = new Client([
'handler' => $stack
]);
$client->post('https://httpbin.org/status/200', [
'body' => '{"key": "val"}'
]);
var_dump($history->getHistory());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment