Created
September 20, 2022 11:44
-
-
Save kobus1998/9d960f63cec72e457b8e368810d4fd42 to your computer and use it in GitHub Desktop.
middleware class for guzzlehttp
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 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