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