summaryrefslogtreecommitdiff
path: root/vendor/open-telemetry/context/Propagation/MultiTextMapPropagator.php
blob: 075fe98fe5f058e835360233e86e730f7a01bbd1 (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
<?php

declare(strict_types=1);

namespace OpenTelemetry\Context\Propagation;

use function array_map;
use function array_merge;
use function array_unique;
use function array_values;
use OpenTelemetry\Context\Context;
use OpenTelemetry\Context\ContextInterface;

final class MultiTextMapPropagator implements TextMapPropagatorInterface
{
    /**
     * @readonly
     *
     * @var list<TextMapPropagatorInterface>
     */
    private array $propagators = [];

    /**
     * @readonly
     *
     * @var list<string>
     */
    private array $fields;

    /**
     * @no-named-arguments
     *
     * @param list<TextMapPropagatorInterface> $propagators
     */
    public function __construct(array $propagators)
    {
        $this->propagators = $propagators;
        $this->fields = $this->extractFields($propagators);
    }

    public function fields(): array
    {
        return $this->fields;
    }

    public function inject(&$carrier, PropagationSetterInterface $setter = null, ContextInterface $context = null): void
    {
        foreach ($this->propagators as $propagator) {
            $propagator->inject($carrier, $setter, $context);
        }
    }

    public function extract($carrier, PropagationGetterInterface $getter = null, ContextInterface $context = null): ContextInterface
    {
        $context ??= Context::getCurrent();

        foreach ($this->propagators as $propagator) {
            $context = $propagator->extract($carrier, $getter, $context);
        }

        return $context;
    }

    /**
     * @param list<TextMapPropagatorInterface> $propagators
     * @return list<string>
     */
    private function extractFields(array $propagators): array
    {
        return array_values(
            array_unique(
                // Phan seems to struggle here with the variadic argument
                // @phan-suppress-next-line PhanParamTooFewInternalUnpack
                array_merge(
                    ...array_map(
                        static fn (TextMapPropagatorInterface $propagator) => $propagator->fields(),
                        $propagators
                    )
                )
            )
        );
    }
}