give
/
vendor
/
vendor-prefixed
/
stellarwp
/
licensing-api-client
/
src
/
Tracing
/
TraceContext.php
TraceContext.php
74 lines
| 1 | <?php declare(strict_types=1); |
| 2 | |
| 3 | namespace Give\Vendors\LiquidWeb\LicensingApiClient\Tracing; |
| 4 | |
| 5 | /** |
| 6 | * Immutable trace header pair for outbound request propagation. |
| 7 | */ |
| 8 | final class TraceContext |
| 9 | { |
| 10 | private TraceParent $traceParent; |
| 11 | |
| 12 | private ?string $traceState; |
| 13 | |
| 14 | private function __construct(TraceParent $traceParent, ?string $traceState) { |
| 15 | $this->traceParent = $traceParent; |
| 16 | $this->traceState = $traceState; |
| 17 | } |
| 18 | |
| 19 | /** |
| 20 | * Generate a new trace context with a fresh traceparent and no tracestate. |
| 21 | */ |
| 22 | public static function generate(bool $sampled = true): self { |
| 23 | return new self(TraceParent::generate($sampled), null); |
| 24 | } |
| 25 | |
| 26 | /** |
| 27 | * Create a trace context from a validated traceparent and optional tracestate. |
| 28 | */ |
| 29 | public static function fromValues(TraceParent $traceParent, ?string $traceState = null): self { |
| 30 | return new self($traceParent, self::normalizeTraceState($traceState)); |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * Return the traceparent value object. |
| 35 | */ |
| 36 | public function traceParent(): TraceParent { |
| 37 | return $this->traceParent; |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Return the normalized tracestate header when present. |
| 42 | */ |
| 43 | public function traceState(): ?string { |
| 44 | return $this->traceState; |
| 45 | } |
| 46 | |
| 47 | /** |
| 48 | * Return the headers that should be applied to an outbound request. |
| 49 | * |
| 50 | * @return array<string, string> |
| 51 | */ |
| 52 | public function headers(): array { |
| 53 | $headers = [ |
| 54 | 'traceparent' => $this->traceParent->header(), |
| 55 | ]; |
| 56 | |
| 57 | if ($this->traceState !== null) { |
| 58 | $headers['tracestate'] = $this->traceState; |
| 59 | } |
| 60 | |
| 61 | return $headers; |
| 62 | } |
| 63 | |
| 64 | private static function normalizeTraceState(?string $traceState): ?string { |
| 65 | if ($traceState === null) { |
| 66 | return null; |
| 67 | } |
| 68 | |
| 69 | $traceState = trim($traceState); |
| 70 | |
| 71 | return $traceState === '' ? null : $traceState; |
| 72 | } |
| 73 | } |
| 74 |