|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Yii\Debug\Collector; |
|
6
|
|
|
|
|
7
|
|
|
use GuzzleHttp\Psr7\Message; |
|
8
|
|
|
use Psr\Http\Message\RequestInterface; |
|
9
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
10
|
|
|
|
|
11
|
|
|
use function count; |
|
12
|
|
|
|
|
13
|
|
|
final class HttpClientCollector implements CollectorInterface, IndexCollectorInterface |
|
14
|
|
|
{ |
|
15
|
|
|
use CollectorTrait; |
|
16
|
|
|
|
|
17
|
|
|
private array $requests = []; |
|
18
|
|
|
|
|
19
|
|
|
public function getCollected(): array |
|
20
|
|
|
{ |
|
21
|
|
|
return array_merge(...array_values($this->requests)); |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
public function getIndexData(): array |
|
25
|
|
|
{ |
|
26
|
|
|
return [ |
|
27
|
|
|
'http' => [ |
|
28
|
|
|
'count' => array_sum(array_map(static fn ($requests) => is_countable($requests) ? count($requests) : 0, $this->requests)), |
|
29
|
|
|
'totalTime' => array_sum( |
|
30
|
|
|
array_merge( |
|
31
|
|
|
...array_map( |
|
32
|
|
|
static fn (array $entry) => array_column($entry, 'totalTime'), |
|
33
|
|
|
$this->requests |
|
34
|
|
|
) |
|
35
|
|
|
) |
|
36
|
|
|
), |
|
37
|
|
|
], |
|
38
|
|
|
]; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
public function collect(RequestInterface $request, float|string $startTime, string $line, ?string $uniqueId) |
|
42
|
|
|
{ |
|
43
|
|
|
if (!$this->isActive()) { |
|
44
|
|
|
return; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
$this->requests[$uniqueId][] = [ |
|
48
|
|
|
'startTime' => $startTime, |
|
49
|
|
|
'endTime' => $startTime, |
|
50
|
|
|
'totalTime' => 0, |
|
51
|
|
|
'method' => $request->getMethod(), |
|
52
|
|
|
'uri' => $request->getUri()->__toString(), |
|
53
|
|
|
'headers' => $request->getHeaders(), |
|
54
|
|
|
'line' => $line, |
|
55
|
|
|
'response' => null, |
|
56
|
|
|
]; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
public function collectTotalTime(?ResponseInterface $response, float|string $startTime, ?string $uniqueId): void |
|
60
|
|
|
{ |
|
61
|
|
|
if (!$this->isActive()) { |
|
62
|
|
|
return; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
if (!isset($this->requests[$uniqueId]) || !is_array($this->requests[$uniqueId])) { |
|
66
|
|
|
return; |
|
67
|
|
|
} |
|
68
|
|
|
$entry = &$this->requests[$uniqueId][count($this->requests[$uniqueId]) - 1]; |
|
69
|
|
|
if ($response instanceof ResponseInterface) { |
|
70
|
|
|
$entry['responseRaw'] = Message::toString($response); |
|
71
|
|
|
$entry['responseStatus'] = $response->getStatusCode(); |
|
72
|
|
|
Message::rewindBody($response); |
|
73
|
|
|
} |
|
74
|
|
|
$entry['endTime'] = $startTime; |
|
75
|
|
|
$entry['totalTime'] = $entry['endTime'] - $entry['startTime']; |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|