1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace MovingImage\Bundle\VMProApiBundle\EventListener; |
4
|
|
|
|
5
|
|
|
use MovingImage\Bundle\VMProApiBundle\Service\Stopwatch; |
6
|
|
|
use Symfony\Component\HttpFoundation\Response; |
7
|
|
|
use Symfony\Component\HttpKernel\Event\FilterResponseEvent; |
8
|
|
|
use Symfony\Component\HttpKernel\KernelEvents; |
9
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Sets the headers with durations of each API request, as well as the total time for all requests. |
13
|
|
|
*/ |
14
|
|
|
class StopwatchListener implements EventSubscriberInterface |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var Stopwatch |
18
|
|
|
*/ |
19
|
|
|
private $stopwatch; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param Stopwatch $stopwatch |
23
|
|
|
*/ |
24
|
|
|
public function __construct(Stopwatch $stopwatch) |
25
|
|
|
{ |
26
|
|
|
$this->stopwatch = $stopwatch; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param FilterResponseEvent $event |
31
|
|
|
*/ |
32
|
|
|
public function onKernelResponse(FilterResponseEvent $event) |
33
|
|
|
{ |
34
|
|
|
$totalDuration = 0; |
35
|
|
|
foreach ($this->stopwatch->getSections() as $section) { |
36
|
|
|
foreach ($section->getEvents() as $name => $stopwatchEvent) { |
37
|
|
|
$duration = $stopwatchEvent->getDuration(); |
38
|
|
|
$totalDuration += $duration; |
39
|
|
|
$this->setHeader($event->getResponse(), $name, $duration); |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$this->setHeader($event->getResponse(), 'total', $totalDuration); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @return array |
48
|
|
|
*/ |
49
|
|
|
public static function getSubscribedEvents() |
50
|
|
|
{ |
51
|
|
|
return [ |
52
|
|
|
KernelEvents::RESPONSE => 'onKernelResponse', |
53
|
|
|
]; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Sets the header for the specified stage (eg X-API-RESPONSE-GET-VIDEOS). |
58
|
|
|
* |
59
|
|
|
* @param Response $response |
60
|
|
|
* @param string $stage |
61
|
|
|
* @param int $duration |
62
|
|
|
*/ |
63
|
|
|
private function setHeader(Response $response, $stage, $duration) |
64
|
|
|
{ |
65
|
|
|
$headerName = 'X-API-RESPONSE-'.strtoupper($stage); |
66
|
|
|
$response->headers->set($headerName, $duration); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|