slpic/guzzle-http-observing-middleware

将 slepic/http-transfer ObserverInterface 适配到 guzzlehttp/guzzle 中间件的适配器。

1.0.2 2023-10-17 08:05 UTC

This package is auto-updated.

Last update: 2024-09-17 09:59:02 UTC


README

Build Status Style Status

guzzle-http-observing-middleware

ObserverInterfaceslepic/http-transfer 包适配到 guzzlehttp/guzzle 中间件。

packagist

需求

PHP >=5.6

安装

使用 composer 安装。

composer require slepic/guzzle-http-observing-middleware

用法

将来自包 slepic/http-transfer\Slepic\Http\Transfer\Observer\ObserverInterface 的任何实例包装在 \Slepic\Guzzle\Http\ObservingMiddleware\ObservingMiddleware 中,并将其传递给 guzzle 客户端的处理器堆栈。

现在,通过 guzzle 客户端发送的所有请求在请求开始处理和接收到响应时都会被通知。

查看示例,其中我们使用 \Slepic\Http\Transfer\History\HistoryObserver 记录带时间的请求和响应。

$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()));

相关