-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTelemetryRequest.php
More file actions
104 lines (75 loc) · 2.04 KB
/
TelemetryRequest.php
File metadata and controls
104 lines (75 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
declare(strict_types=1);
namespace DragonCode\Telemetry;
use Closure;
use Ramsey\Uuid\UuidFactory;
use Symfony\Component\HttpFoundation\Request;
use function is_int;
class TelemetryRequest
{
public function __construct(
protected Request $request,
protected TelemetryHeader $header,
) {}
public function userId(int|string|null $id): static
{
$id ??= $this->getUserId();
$this->set($this->header->userId, $id);
return $this;
}
public function getUserId(): string
{
if ($id = $this->get($this->header->userId)) {
return $id;
}
return '0';
}
public function ip(?string $ip = null): static
{
$ip ??= $this->getIp();
$this->set($this->header->ip, $ip);
return $this;
}
public function getIp(): string
{
if ($ip = $this->get($this->header->ip)) {
return $ip;
}
return $this->get('HTTP_X_REAL_IP') ?: $this->request->getClientIp();
}
public function traceId(?string $id = null): static
{
$id ??= $this->getTraceId();
$this->set($this->header->traceId, $id);
return $this;
}
public function getTraceId(): string
{
if ($id = $this->get($this->header->traceId)) {
return $id;
}
return (new UuidFactory)->uuid4()->toString();
}
public function custom(string $header, Closure $callback): static
{
$value = $this->get($header) ?: $callback($this->getRequest());
$this->set($header, $value);
return $this;
}
public function getRequest(): Request
{
return $this->request;
}
protected function set(string $key, array|int|string|null $value): static
{
if (is_int($value)) {
$value = (string) $value;
}
$this->request->headers->set($key, $value);
return $this;
}
protected function get(string $key): array|string|null
{
return $this->request->headers->get($key);
}
}