1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace jin2chen\ApiBundle\EventSubscriber; |
6
|
|
|
|
7
|
|
|
use Monolog\Processor\ProcessorInterface; |
8
|
|
|
use Ramsey\Uuid\Uuid; |
9
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
10
|
|
|
use Symfony\Component\HttpKernel\Event\RequestEvent; |
11
|
|
|
use Symfony\Component\HttpKernel\Event\ResponseEvent; |
12
|
|
|
use Symfony\Component\HttpKernel\KernelEvents; |
13
|
|
|
use Symfony\Contracts\Service\ResetInterface; |
14
|
|
|
|
15
|
|
|
use function is_null; |
16
|
|
|
|
17
|
|
|
class RequestIdSubscriber implements EventSubscriberInterface, ProcessorInterface, ResetInterface |
18
|
|
|
{ |
19
|
|
|
private string $header = 'X-Request-Id'; |
20
|
|
|
/** |
21
|
|
|
* @var array{request_id: string} |
22
|
|
|
*/ |
23
|
|
|
private array $data; |
24
|
|
|
|
25
|
9 |
|
public function __construct(?string $header = null) |
26
|
|
|
{ |
27
|
9 |
|
$this->reset(); |
28
|
9 |
|
if (!is_null($header)) { |
29
|
9 |
|
$this->header = $header; |
30
|
|
|
} |
31
|
9 |
|
} |
32
|
|
|
|
33
|
9 |
|
public function __invoke(array $record): array |
34
|
|
|
{ |
35
|
9 |
|
$record['extra']['request_id'] = $this->data['request_id']; |
36
|
|
|
|
37
|
9 |
|
return $record; |
38
|
|
|
} |
39
|
|
|
|
40
|
2 |
|
public static function getSubscribedEvents(): array |
41
|
|
|
{ |
42
|
|
|
return [ |
43
|
2 |
|
KernelEvents::REQUEST => ['onKernelRequest', 1024], |
44
|
|
|
KernelEvents::RESPONSE => 'onKernelResponse', |
45
|
|
|
KernelEvents::TERMINATE => 'onKernelTerminate', |
46
|
|
|
]; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @Callback |
51
|
|
|
* @see getSubscribedEvents() |
52
|
|
|
*/ |
53
|
9 |
|
public function onKernelRequest(RequestEvent $event): void |
54
|
|
|
{ |
55
|
9 |
|
$request = $event->getRequest(); |
56
|
|
|
|
57
|
9 |
|
if ($request->headers->has($this->header)) { |
58
|
1 |
|
$this->data['request_id'] = (string) $request->headers->get($this->header); |
59
|
1 |
|
return; |
60
|
|
|
} |
61
|
|
|
|
62
|
9 |
|
$this->data['request_id'] = Uuid::uuid4()->toString(); |
63
|
9 |
|
$request->headers->set($this->header, $this->data['request_id']); |
64
|
9 |
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @Callback |
68
|
|
|
* @see getSubscribedEvents() |
69
|
|
|
* @param ResponseEvent $event |
70
|
|
|
*/ |
71
|
9 |
|
public function onKernelResponse(ResponseEvent $event): void |
72
|
|
|
{ |
73
|
9 |
|
$event->getResponse()->headers->set($this->header, $this->data['request_id']); |
74
|
9 |
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @Callback |
78
|
|
|
* @see getSubscribedEvents() |
79
|
|
|
*/ |
80
|
9 |
|
public function onKernelTerminate(): void |
81
|
|
|
{ |
82
|
9 |
|
$this->reset(); |
83
|
9 |
|
} |
84
|
|
|
|
85
|
9 |
|
final public function reset(): void |
86
|
|
|
{ |
87
|
9 |
|
$this->data = [ |
88
|
|
|
'request_id' => '', |
89
|
|
|
]; |
90
|
9 |
|
} |
91
|
|
|
} |
92
|
|
|
|