-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGuzzleHttpClientMessage.php
More file actions
89 lines (78 loc) · 2.8 KB
/
GuzzleHttpClientMessage.php
File metadata and controls
89 lines (78 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
namespace WebmanTech\Logger\Message;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Promise\Create;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Throwable;
use WebmanTech\Logger\Helper\StringHelper;
/**
* Guzzle HttpClient 请求日志
*/
class GuzzleHttpClientMessage extends BaseHttpClientMessage
{
protected function getResponseStatus(mixed $response): int
{
if (!$response instanceof ResponseInterface) {
return 0;
}
return $response->getStatusCode();
}
protected function getResponseContent(mixed $response, int $limitLength): string
{
if (!$response instanceof ResponseInterface) {
return '[Response Type error]';
}
try {
$content = $response->getBody()->getContents();
} catch (Throwable $e) {
return '[Response Content error: ' . $e->getMessage() . ']';
}
return StringHelper::limit($content, $limitLength);
}
/**
* 作为 middleware 时的入口
*/
public function middleware(): \Closure
{
return function (callable $handler) {
return function (RequestInterface $request, array $options) use ($handler) {
$this->markRequestStart($request->getMethod(), (string)$request->getUri(), $options);
try {
/** @var PromiseInterface $promise */
$promise = $handler($request, $options);
} catch (Throwable $reason) {
[$response, $exception] = $this->resolveRejectedReason($reason);
$this->markResponseEnd($response, $exception);
throw $reason;
}
return $promise->then(
function (ResponseInterface $response) {
$this->markResponseEnd($response);
return $response;
},
function (mixed $reason) {
[$response, $exception] = $this->resolveRejectedReason($reason);
$this->markResponseEnd($response, $exception);
return Create::rejectionFor($reason);
}
);
};
};
}
/**
* @return array{0: ResponseInterface|null, 1: Throwable|null}
*/
protected function resolveRejectedReason(mixed $reason): array
{
$response = null;
$exception = $reason instanceof Throwable ? $reason : null;
if ($reason instanceof RequestException) {
$response = $reason->getResponse();
} elseif ($reason instanceof ResponseInterface) {
$response = $reason;
}
return [$response, $exception];
}
}