Completed
Push — master ( 293a61...e1a0d3 )
by
unknown
12s
created

StopwatchListener::getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
ccs 0
cts 3
cp 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
crap 2
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
     * @var bool
23
     */
24
    private $enabled;
25
26
    /**
27
     * @param Stopwatch $stopwatch
28
     * @param bool      $enabled   (if false, this listener will be effectively bypassed)
29
     */
30 4
    public function __construct(Stopwatch $stopwatch, $enabled)
31
    {
32 4
        $this->stopwatch = $stopwatch;
33 4
        $this->enabled = $enabled;
34 4
    }
35
36
    /**
37
     * @param FilterResponseEvent $event
38
     */
39 4
    public function onKernelResponse(FilterResponseEvent $event)
40
    {
41 4
        if (!$this->enabled) {
42 2
            return;
43
        }
44
45 2
        $totalDuration = 0;
46
47 2
        foreach ($this->stopwatch->getEvents() as $name => $stopwatchEvent) {
48 2
            $duration = $stopwatchEvent->getDuration();
49 2
            $totalDuration += $duration;
50 2
            $this->setHeader($event->getResponse(), $name, $duration);
51 2
        }
52
53 2
        $this->setHeader($event->getResponse(), 'total', $totalDuration);
54 2
    }
55
56
    /**
57
     * @return array
58
     */
59
    public static function getSubscribedEvents()
60
    {
61
        return [
62
            KernelEvents::RESPONSE => 'onKernelResponse',
63
        ];
64
    }
65
66
    /**
67
     * Sets the header for the specified stage (eg X-API-RESPONSE-GET-VIDEOS).
68
     *
69
     * @param Response $response
70
     * @param string   $stage
71
     * @param int      $duration
72
     */
73 2
    private function setHeader(Response $response, $stage, $duration)
74
    {
75 2
        $headerName = 'X-API-RESPONSE-'.strtoupper($stage);
76 2
        $response->headers->set($headerName, $duration);
77 2
    }
78
}
79