mapResponse

  • GuzzleHttp\Middleware::mapResponse
  • Accepts a closure that can inspect or modify a response after it is received
  • The response is an instance of Psr\Http\Message\ResponseInterface (PSR-7)
PendingRequest::macro('withOnlyData', function (): PendingRequest {
    /** @var $this PendingRequest */
    return $this->withMiddleware(
        Middleware::mapResponse(
            function (ResponseInterface $response) use ($closure) {
                $body = collect(
                    json_decode($response->getBody()->getContents(), true)
                );

                if ($body->has('data')) {
                    $newBody = json_encode($body->get('data'));
                }

                $streamBody = fopen('data://text/plain,' . $newBody, 'r');

                return $response
                    ->withBody(new Stream($streamBody));
            }
        )
    );
});

← / → navigate · N notes · Esc exit