Test Failed
Pull Request — master (#11)
by
unknown
13:22
created

StopwatchListener   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
c 1
b 0
f 0
lcom 0
cbo 6
dl 0
loc 55
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A onKernelResponse() 0 13 3
A getSubscribedEvents() 0 6 1
A setHeader() 0 5 1
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