1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace EightPoints\Bundle\GuzzleBundle\Middleware; |
4
|
|
|
|
5
|
|
|
use EightPoints\Bundle\GuzzleBundle\Log\Logger; |
6
|
|
|
use EightPoints\Bundle\GuzzleBundle\Log\LoggerInterface; |
7
|
|
|
use EightPoints\Bundle\GuzzleBundle\DataCollector\HttpDataCollector; |
8
|
|
|
use Psr\Http\Message\RequestInterface; |
9
|
|
|
use GuzzleHttp\TransferStats; |
10
|
|
|
|
11
|
|
|
class RequestTimeMiddleware |
12
|
|
|
{ |
13
|
|
|
/** @var \EightPoints\Bundle\GuzzleBundle\Log\LoggerInterface */ |
14
|
|
|
protected $logger; |
15
|
|
|
|
16
|
|
|
/** @var \EightPoints\Bundle\GuzzleBundle\DataCollector\HttpDataCollector */ |
17
|
|
|
private $dataCollector; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @param \EightPoints\Bundle\GuzzleBundle\Log\LoggerInterface $logger |
21
|
|
|
* @param \EightPoints\Bundle\GuzzleBundle\DataCollector\HttpDataCollector $dataCollector |
22
|
|
|
*/ |
23
|
|
|
public function __construct(LoggerInterface $logger, HttpDataCollector $dataCollector) |
24
|
|
|
{ |
25
|
|
|
$this->logger = $logger; |
26
|
|
|
$this->dataCollector = $dataCollector; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param callable $handler |
31
|
|
|
* |
32
|
|
|
* @return \Closure |
33
|
|
|
*/ |
34
|
|
|
public function __invoke(callable $handler) : \Closure |
35
|
|
|
{ |
36
|
|
|
return function (RequestInterface $request, array $options) use ($handler) { |
37
|
|
|
$options['on_stats'] = $this->getOnStatsCallback( |
38
|
|
|
isset($options['on_stats']) ? $options['on_stats'] : null, |
39
|
|
|
isset($options['request_id']) ? $options['request_id'] : null |
40
|
|
|
); |
41
|
|
|
|
42
|
|
|
// Continue the handler chain. |
43
|
|
|
return $handler($request, $options); |
44
|
|
|
}; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Create callback for on_stats options. |
49
|
|
|
* If request has on_stats option, it will be called inside of this callback. |
50
|
|
|
* |
51
|
|
|
* @param null|callable $initialOnStats |
52
|
|
|
* @param null|string $requestId |
53
|
|
|
* |
54
|
|
|
* @return \Closure |
55
|
|
|
*/ |
56
|
|
|
protected function getOnStatsCallback(?callable $initialOnStats, ?string $requestId) : \Closure |
57
|
|
|
{ |
58
|
|
|
return function (TransferStats $stats) use ($initialOnStats, $requestId) { |
59
|
|
|
if (is_callable($initialOnStats)) { |
60
|
|
|
call_user_func($initialOnStats, $stats); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
$this->dataCollector->addTotalTime((float)$stats->getTransferTime()); |
64
|
|
|
|
65
|
|
|
if (($this->logger instanceof Logger) && $requestId) { |
66
|
|
|
$this->logger->addTransferTimeByRequestId($requestId, (float)$stats->getTransferTime()); |
67
|
|
|
} |
68
|
|
|
}; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|