|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* @codingStandardsIgnoreStart |
|
4
|
|
|
* |
|
5
|
|
|
* @author Barney Hanlon <[email protected]> |
|
6
|
|
|
* @copyright Barney Hanlon 2017 |
|
7
|
|
|
* @license https://opensource.org/licenses/MIT |
|
8
|
|
|
* |
|
9
|
|
|
* @codingStandardsIgnoreEnd |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Shrikeh\GuzzleMiddleware\TimerLogger\RequestTimers; |
|
13
|
|
|
|
|
14
|
|
|
use Psr\Http\Message\RequestInterface; |
|
15
|
|
|
use Shrikeh\GuzzleMiddleware\TimerLogger\RequestTimers\Exception\RequestNotFoundException; |
|
16
|
|
|
use Shrikeh\GuzzleMiddleware\TimerLogger\Timer\Stopwatch; |
|
17
|
|
|
use SplObjectStorage; |
|
18
|
|
|
use UnexpectedValueException; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* Class TimerHandler. |
|
22
|
|
|
*/ |
|
23
|
|
|
final class RequestTimers implements RequestTimersInterface |
|
24
|
|
|
{ |
|
25
|
|
|
/** |
|
26
|
|
|
* @var \SplObjectStorage |
|
27
|
|
|
*/ |
|
28
|
|
|
private $requestTimers; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* TimerHandler constructor. |
|
32
|
|
|
*/ |
|
33
|
|
|
public function __construct() |
|
34
|
|
|
{ |
|
35
|
|
|
$this->requestTimers = new SplObjectStorage(); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* {@inheritdoc} |
|
40
|
|
|
*/ |
|
41
|
|
|
public function start(RequestInterface $request) |
|
42
|
|
|
{ |
|
43
|
|
|
if (!$this->requestTimers->contains($request)) { |
|
44
|
|
|
$this->requestTimers->attach( |
|
45
|
|
|
$request, |
|
46
|
|
|
Stopwatch::startStopWatch() |
|
47
|
|
|
); |
|
48
|
|
|
} |
|
49
|
|
|
$timer = $this->timerFor($request); |
|
50
|
|
|
$timer->start(); |
|
51
|
|
|
|
|
52
|
|
|
return $timer; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* {@inheritdoc} |
|
57
|
|
|
*/ |
|
58
|
|
|
public function stop(RequestInterface $request) |
|
59
|
|
|
{ |
|
60
|
|
|
$timer = $this->timerFor($request); |
|
61
|
|
|
$timer->stop(); |
|
62
|
|
|
|
|
63
|
|
|
return $timer; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
/** |
|
67
|
|
|
* {@inheritdoc} |
|
68
|
|
|
*/ |
|
69
|
|
|
public function duration(RequestInterface $request) |
|
70
|
|
|
{ |
|
71
|
|
|
return $this->timerFor($request)->duration(); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
/** |
|
75
|
|
|
* @param \Psr\Http\Message\RequestInterface $request The request to retrieve a timer for |
|
76
|
|
|
* |
|
77
|
|
|
* @return \Shrikeh\GuzzleMiddleware\TimerLogger\Timer\TimerInterface |
|
78
|
|
|
*/ |
|
79
|
|
|
private function timerFor(RequestInterface $request) |
|
80
|
|
|
{ |
|
81
|
|
|
try { |
|
82
|
|
|
return $this->requestTimers->offsetGet($request); |
|
83
|
|
|
} catch (UnexpectedValueException $e) { |
|
84
|
|
|
throw new RequestNotFoundException( |
|
85
|
|
|
$request, |
|
86
|
|
|
$e |
|
87
|
|
|
); |
|
88
|
|
|
} |
|
89
|
|
|
} |
|
90
|
|
|
} |
|
91
|
|
|
|