Last active
November 2, 2022 18:06
-
-
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.
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 | |
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