slepic/guzzle-http-observing-middleware

Adapter of slepic/http-transfer ObserverInterface to guzzlehttp/guzzle middleware.

1.0.0 2021-03-10 13:19 UTC

This package is auto-updated.

Last update: 2021-05-10 13:43:50 UTC


README

Build Status Style Status

guzzle-http-observing-middleware

Adapter of ObserverInterface from slepic/http-transfer package to guzzlehttp/guzzle middleware.

packagist

Requirements

PHP >=5.6

Installation

Install with composer.

composer require slepic/guzzle-http-observing-middleware

Usage

Wrap any instance of \Slepic\Http\Transfer\Observer\ObserverInterface from package slepic/http-transfer in the \Slepic\Guzzle\Http\ObservingMiddleware\ObservingMiddleware and pass it to handler stack of your guzzle client.

All requests sent through the guzzle client will now be notified when requests are starting to get processed and when responses are received.

See an example where we use \Slepic\Http\Transfer\History\HistoryObserver to log requests and responses with timing.

$storage = new ArrayStorage();
$observer = new HistoryObserver($storage);
$middleware = new ObservingMiddleware($observer);

$client = new \GuzzleHttp\Client();
$client->getConfig('handler')->unshift($middleware);

try {
$response = $client->request($method, $uri);
} catch (\Exception $e) {
  assert($storage[0]->getRequest()->getMethod() === $method);
  assert((string)($storage[0]->getRequest()->getUri()) === $uri);
  assert($storage[0]->getException() === $e);
  assert(0 < ($storage[0]->getEndTime() - $storage[0]->getStartTime()));
  throw $e;
}

assert($storage[0]->getRequest()->getMethod() === 'GET');
assert((string)($storage[0]->getRequest()->getUri()) === $uri);
assert($storage[0]->getResponse() === $response);
assert(0 < ($storage[0]->getEndTime() - $storage[0]->getStartTime()));

Related