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
|
|
|
/** @var array{extra: array} $record */ |
36
|
9 |
|
$record['extra']['request_id'] = $this->data['request_id']; |
37
|
|
|
|
38
|
9 |
|
return $record; |
39
|
|
|
} |
40
|
|
|
|
41
|
2 |
|
public static function getSubscribedEvents(): array |
42
|
|
|
{ |
43
|
|
|
return [ |
44
|
2 |
|
KernelEvents::REQUEST => ['onRequest', 1024], |
45
|
|
|
KernelEvents::RESPONSE => 'onResponse', |
46
|
|
|
KernelEvents::TERMINATE => 'onTerminate', |
47
|
|
|
]; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @Callback |
52
|
|
|
* @see getSubscribedEvents() |
53
|
|
|
*/ |
54
|
9 |
|
public function onRequest(RequestEvent $event): void |
55
|
|
|
{ |
56
|
9 |
|
$request = $event->getRequest(); |
57
|
|
|
|
58
|
9 |
|
if ($request->headers->has($this->header)) { |
59
|
1 |
|
$this->data['request_id'] = (string) $request->headers->get($this->header); |
60
|
1 |
|
return; |
61
|
|
|
} |
62
|
|
|
|
63
|
9 |
|
$this->data['request_id'] = Uuid::uuid4()->toString(); |
64
|
9 |
|
$request->headers->set($this->header, $this->data['request_id']); |
65
|
9 |
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @Callback |
69
|
|
|
* @see getSubscribedEvents() |
70
|
|
|
* @param ResponseEvent $event |
71
|
|
|
*/ |
72
|
9 |
|
public function onResponse(ResponseEvent $event): void |
73
|
|
|
{ |
74
|
9 |
|
$event->getResponse()->headers->set($this->header, $this->data['request_id']); |
75
|
9 |
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @Callback |
79
|
|
|
* @see getSubscribedEvents() |
80
|
|
|
*/ |
81
|
9 |
|
public function onTerminate(): void |
82
|
|
|
{ |
83
|
9 |
|
$this->reset(); |
84
|
9 |
|
} |
85
|
|
|
|
86
|
9 |
|
final public function reset(): void |
87
|
|
|
{ |
88
|
9 |
|
$this->data = [ |
89
|
|
|
'request_id' => '', |
90
|
|
|
]; |
91
|
9 |
|
} |
92
|
|
|
} |
93
|
|
|
|