Skip to content

Instantly share code, notes, and snippets.

@eexit
Last active November 2, 2022 18:06
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 eexit/a60e51dccd0f91cdc54db77e3ec2e369 to your computer and use it in GitHub Desktop.
Save eexit/a60e51dccd0f91cdc54db77e3ec2e369 to your computer and use it in GitHub Desktop.
The Guzzle 7 BodyRewinderMiddleware allows to rewind a body which would have been read and not rewinded by previous middlewares.
<?php
declare(strict_types=1);
namespace App\GuzzleMiddleware;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Message;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
/**
* Usage:
* $stack = HandlerStack::create();
* $stack->push(BodyRewinderMiddleware::bind(), 'bodyrewinder');
* Push the rest of your middlewares...
*/
final class BodyRewinderMiddleware
{
/**
* @var callable(RequestInterface, array<mixed>): PromiseInterface
*/
private $handler;
/**
* @param callable(RequestInterface, array<mixed>): PromiseInterface $handler
*/
public function __construct(callable $handler)
{
$this->handler = $handler;
}
public static function bind(): callable
{
return static function (callable $handler): self {
return new self($handler);
};
}
/**
* @param array<mixed> $options
*/
public function __invoke(RequestInterface $request, array $options): PromiseInterface
{
$handler = $this->handler;
Message::rewindBody($request);
return $handler($request, $options)->then(static function (ResponseInterface $response): ResponseInterface {
Message::rewindBody($response);
return $response;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment