@@ -39,11 +39,19 @@ public static function getOpentelemetryValues(): array
3939 carrier: $ appendContext
4040 );
4141
42- if ($ appendContext && is_array ($ appendContext )) {
42+ if ($ appendContext && isset ($ appendContext ['x-b3-traceid ' ])) {
43+ /** @psalm-suppress PossiblyInvalidArgument */
4344 $ traceparent = self ::convertB3ToW3C ($ appendContext );
4445
4546 return ['traceparent ' => $ traceparent ];
4647 }
48+
49+ if ($ appendContext && isset ($ appendContext ['uber-trace-id ' ])) {
50+ /** @psalm-suppress PossiblyInvalidArgument */
51+ $ traceparent = self ::convertUberTraceIdToTraceparent ($ appendContext );
52+
53+ return ['traceparent ' => $ traceparent ];
54+ }
4755 }
4856
4957 return [];
@@ -65,4 +73,26 @@ private static function convertB3ToW3C(array $b3Context): string
6573 $ version = '00 ' ;
6674 return "{$ version }- {$ traceId }- {$ spanId }- {$ sampled }" ;
6775 }
76+
77+ /**
78+ * Converts an Uber Trace ID to a W3C Traceparent format.
79+ *
80+ * @param array $uberContext An associative array containing the Uber Trace ID with the key 'uber-trace-id'.
81+ * Example: ['uber-trace-id' => '7316935077496437249:658af9afaac53a01:0:0']
82+ *
83+ * @return string The W3C Traceparent formatted string.
84+ * Example: '00-00000000000007316935077496437249-658af9afaac53a01-00'
85+ */
86+ private static function convertUberTraceIdToTraceparent (array $ uberContext ): string
87+ {
88+ [$ traceId , $ spanId , $ parentSpanId , $ flags ] = explode (': ' , (string ) $ uberContext ['uber-trace-id ' ]);
89+
90+ $ traceId = str_pad ($ traceId , 32 , '0 ' , STR_PAD_LEFT );
91+ $ spanId = str_pad ($ spanId , 16 , '0 ' , STR_PAD_LEFT );
92+ $ sampled = $ flags === '1 ' ? '01 ' : '00 ' ;
93+
94+ // W3C Traceparent format
95+ $ version = '00 ' ;
96+ return sprintf ('%s-%s-%s-%s ' , $ version , $ traceId , $ spanId , $ sampled );
97+ }
6898}
0 commit comments