AddsRequestIdOnResponse::onResponse()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Arki\RequestId library.
5
 *
6
 * (c) Alexandru Furculita <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.md.
10
 */
11
12
namespace Arki\RequestId\Integrations\Symfony\EventSubscribers;
13
14
use Arki\RequestId\Providers\RequestIdProvider;
15
use Arki\RequestId\RequestId;
16
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
17
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
18
use Symfony\Component\HttpKernel\HttpKernelInterface;
19
use Symfony\Component\HttpKernel\KernelEvents;
20
21
/**
22
 * Adds request ID on responses.
23
 */
24
final class AddsRequestIdOnResponse implements EventSubscriberInterface
25
{
26
    /**
27
     * @var RequestIdProvider
28
     */
29
    private $idProvider;
30
    /**
31
     * @var string
32
     */
33
    private $responseHeader;
34
35
    /**
36
     * @param RequestIdProvider $idProvider
37
     * @param string            $responseHeader
38
     */
39
    public function __construct(RequestIdProvider $idProvider, $responseHeader = RequestId::HEADER_NAME)
40
    {
41
        $this->idProvider = $idProvider;
42
        $this->responseHeader = $responseHeader;
43
    }
44
45
    /**
46
     * @param FilterResponseEvent $event
47
     */
48
    public function onResponse(FilterResponseEvent $event)
49
    {
50
        if (!$event->getRequestType() === HttpKernelInterface::MASTER_REQUEST) {
51
            return;
52
        }
53
54
        if (null === $this->idProvider->getRequestId()) {
55
            return;
56
        }
57
58
        $event->getResponse()->headers->set($this->responseHeader, $this->idProvider->getRequestId());
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    public static function getSubscribedEvents()
65
    {
66
        return [KernelEvents::RESPONSE => ['onResponse', -200]];
67
    }
68
}
69