summaryrefslogtreecommitdiff
path: root/vendor/jonahgeorge/jaeger-client-php/src/Jaeger/Codec/ZipkinCodec.php
blob: 1ea5d7c0b001a15fc7fe6f43855443a4a454da9a (plain)
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
<?php

namespace Jaeger\Codec;

use Jaeger\SpanContext;

use const Jaeger\DEBUG_FLAG;
use const Jaeger\SAMPLED_FLAG;

class ZipkinCodec implements CodecInterface
{
    const SAMPLED_NAME = 'X-B3-Sampled';
    const TRACE_ID_NAME = 'X-B3-TraceId';
    const SPAN_ID_NAME = 'X-B3-SpanId';
    const PARENT_ID_NAME = 'X-B3-ParentSpanId';
    const FLAGS_NAME = 'X-B3-Flags';

    /**
     * {@inheritdoc}
     *
     * @see \Jaeger\Tracer::inject
     *
     * @param SpanContext $spanContext
     * @param mixed $carrier
     *
     * @return void
     */
    public function inject(SpanContext $spanContext, &$carrier)
    {
        $carrier[self::TRACE_ID_NAME] = dechex($spanContext->getTraceId());
        $carrier[self::SPAN_ID_NAME] = dechex($spanContext->getSpanId());
        if ($spanContext->getParentId() != null) {
            $carrier[self::PARENT_ID_NAME] = dechex($spanContext->getParentId());
        }
        $carrier[self::FLAGS_NAME] = (int) $spanContext->getFlags();
    }

    /**
     * {@inheritdoc}
     *
     * @see \Jaeger\Tracer::extract
     *
     * @param mixed $carrier
     * @return SpanContext|null
     */
    public function extract($carrier)
    {
        $traceId = "0";
        $spanId = "0";
        $parentId = "0";
        $flags = 0;

        if (isset($carrier[strtolower(self::SAMPLED_NAME)])) {
            if ($carrier[strtolower(self::SAMPLED_NAME)] === "1" ||
                strtolower($carrier[strtolower(self::SAMPLED_NAME)] === "true")
            ) {
                $flags = $flags | SAMPLED_FLAG;
            }
        }

        if (isset($carrier[strtolower(self::TRACE_ID_NAME)])) {
            $traceId =  CodecUtility::hexToInt64($carrier[strtolower(self::TRACE_ID_NAME)], 16, 10);
        }

        if (isset($carrier[strtolower(self::PARENT_ID_NAME)])) {
            $parentId =  CodecUtility::hexToInt64($carrier[strtolower(self::PARENT_ID_NAME)], 16, 10);
        }

        if (isset($carrier[strtolower(self::SPAN_ID_NAME)])) {
            $spanId =  CodecUtility::hexToInt64($carrier[strtolower(self::SPAN_ID_NAME)], 16, 10);
        }

        if (isset($carrier[strtolower(self::FLAGS_NAME)])) {
            if ($carrier[strtolower(self::FLAGS_NAME)] === "1") {
                $flags = $flags | DEBUG_FLAG;
            }
        }

        if ($traceId != "0" && $spanId != "0") {
            return new SpanContext($traceId, $spanId, $parentId, $flags);
        }

        return null;
    }
}