Skip to content

Commit a9ce1e3

Browse files
Add custom method to TelemetryRequest for handling custom headers and update README.md with usage examples
1 parent 076869a commit a9ce1e3

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

README.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,43 @@ telemetry($request, $user->id);
4646
telemetry($request);
4747
```
4848

49+
### Custom Headers
50+
51+
```php
52+
use DragonCode\Telemetry\TelemetryHeader;
53+
use DragonCode\Telemetry\TelemetryRequest;
54+
use Symfony\Component\HttpFoundation\Request;
55+
56+
/** @var Request $request */
57+
$request = /* ... */;
58+
59+
$telemetry = new TelemetryRequest($request, new TelemetryHeader);
60+
61+
function telemetry(Request $request, ?int $userId = null): Request
62+
{
63+
return (new TelemetryRequest($request, new TelemetryHeader))
64+
->userId($userId)
65+
->ip()
66+
->trackId()
67+
->custom('Some-Header', fn (Request $request) => 1234
68+
->getRequest();
69+
}
70+
```
71+
72+
```php
73+
$item = telemetry($request);
74+
75+
return $item->headers->get('Some-Header'); // 1234
76+
```
77+
78+
```php
79+
$request->headers->set('Some-Header', 'qwerty');
80+
81+
$item = telemetry($request);
82+
83+
return $item->headers->get('Some-Header'); // qwerty
84+
```
85+
4986
### Custom Header Names
5087

5188
```php

src/TelemetryRequest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace DragonCode\Telemetry;
66

7+
use Closure;
78
use Ramsey\Uuid\UuidFactory;
89
use Symfony\Component\HttpFoundation\Request;
910

@@ -70,6 +71,15 @@ public function getTrackId(): string
7071
return (new UuidFactory)->uuid4()->toString();
7172
}
7273

74+
public function custom(string $header, Closure $callback): static
75+
{
76+
$value = $this->get($header) ?: $callback($this->getRequest());
77+
78+
$this->set($header, $value);
79+
80+
return $this;
81+
}
82+
7383
public function getRequest(): Request
7484
{
7585

0 commit comments

Comments
 (0)