1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Phauthentic\CorrelationIdBundle\EventSubscriber; |
6
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use Exception; |
9
|
|
|
use Phauthentic\Infrastructure\Utils\CorrelationID; |
10
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
11
|
|
|
use Symfony\Component\HttpKernel\Event\RequestEvent; |
12
|
|
|
use Symfony\Component\HttpKernel\Event\ResponseEvent; |
13
|
|
|
use Symfony\Component\HttpKernel\KernelEvents; |
14
|
|
|
|
15
|
|
|
class CorrelationIdSubscriber implements EventSubscriberInterface |
16
|
|
|
{ |
17
|
|
|
private string $requestHeaderName = 'X-Correlation-ID'; |
18
|
|
|
private string $responseHeaderName = 'X-Correlation-ID'; |
19
|
|
|
private bool $passthrough = false; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param array<string, mixed> $config |
23
|
|
|
* @return void |
24
|
|
|
*/ |
25
|
|
|
public function __construct(array $config = []) |
26
|
|
|
{ |
27
|
|
|
if (isset($config['request_header_name'])) { |
28
|
|
|
$this->requestHeaderName = (string)$config['request_header_name']; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
if (isset($config['response_header_name'])) { |
32
|
|
|
$this->responseHeaderName = (string)$config['response_header_name']; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
if (isset($config['pass_through'])) { |
36
|
|
|
$this->passthrough = (bool)$config['pass_through']; |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @SuppressWarnings(PHPMD.StaticAccess) |
42
|
|
|
* |
43
|
|
|
* @param RequestEvent $event |
44
|
|
|
* @return void |
45
|
|
|
*/ |
46
|
|
|
public function onKernelRequest(RequestEvent $event): void |
47
|
|
|
{ |
48
|
|
|
$event->getRequest()->attributes->set($this->requestHeaderName, CorrelationID::toString()); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @SuppressWarnings(PHPMD.StaticAccess) |
53
|
|
|
* |
54
|
|
|
* @param ResponseEvent $event |
55
|
|
|
* @return void |
56
|
|
|
* @throws InvalidArgumentException |
57
|
|
|
* @throws Exception |
58
|
|
|
*/ |
59
|
|
|
public function onKernelResponse(ResponseEvent $event): void |
60
|
|
|
{ |
61
|
|
|
if ( |
62
|
|
|
$this->passthrough |
63
|
|
|
&& $event->getRequest()->headers->has($this->requestHeaderName) |
64
|
|
|
) { |
65
|
|
|
$event->getResponse()->headers->set( |
66
|
|
|
$this->responseHeaderName, |
67
|
|
|
$event->getRequest()->headers->get($this->requestHeaderName) |
68
|
|
|
); |
69
|
|
|
|
70
|
|
|
return; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
$event->getResponse()->headers->set($this->responseHeaderName, CorrelationID::toString()); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
public static function getSubscribedEvents(): array |
77
|
|
|
{ |
78
|
|
|
return [ |
79
|
|
|
KernelEvents::REQUEST => ['onKernelRequest', 255], |
80
|
|
|
KernelEvents::RESPONSE => ['onKernelResponse', -255] |
81
|
|
|
]; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|