@@ -39,11 +39,19 @@ public static function getOpentelemetryValues(): array
39
39
carrier: $ appendContext
40
40
);
41
41
42
- if ($ appendContext && is_array ($ appendContext )) {
42
+ if ($ appendContext && isset ($ appendContext ['x-b3-traceid ' ])) {
43
+ /** @psalm-suppress PossiblyInvalidArgument */
43
44
$ traceparent = self ::convertB3ToW3C ($ appendContext );
44
45
45
46
return ['traceparent ' => $ traceparent ];
46
47
}
48
+
49
+ if ($ appendContext && isset ($ appendContext ['uber-trace-id ' ])) {
50
+ /** @psalm-suppress PossiblyInvalidArgument */
51
+ $ traceparent = self ::convertUberTraceIdToTraceparent ($ appendContext );
52
+
53
+ return ['traceparent ' => $ traceparent ];
54
+ }
47
55
}
48
56
49
57
return [];
@@ -65,4 +73,26 @@ private static function convertB3ToW3C(array $b3Context): string
65
73
$ version = '00 ' ;
66
74
return "{$ version }- {$ traceId }- {$ spanId }- {$ sampled }" ;
67
75
}
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
+ }
68
98
}
0 commit comments