|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace OpenTelemetry\Context\Propagation; |
| 6 | + |
| 7 | +use InvalidArgumentException; |
| 8 | + |
| 9 | +/** |
| 10 | + * @see https://github.com/open-telemetry/opentelemetry-specification/blob/v1.44.0/specification/context/env-carriers.md |
| 11 | + * |
| 12 | + * Default implementation of {@see ExtendedPropagationGetterInterface} and {@see PropagationSetterInterface}. |
| 13 | + * This type uses environment variables as a carrier for context propagation. |
| 14 | + * It is provided to {@see TextMapPropagatorInterface::inject()} or {@see TextMapPropagatorInterface::extract()}. |
| 15 | + */ |
| 16 | +final class EnvironmentGetterSetter implements ExtendedPropagationGetterInterface, PropagationSetterInterface |
| 17 | +{ |
| 18 | + private static ?self $instance = null; |
| 19 | + |
| 20 | + public static function getInstance(): self |
| 21 | + { |
| 22 | + return self::$instance ??= new self(); |
| 23 | + } |
| 24 | + |
| 25 | + #[\Override] |
| 26 | + public function keys($carrier): array |
| 27 | + { |
| 28 | + $envs = getenv(); |
| 29 | + if (!is_array($envs) || $envs === []) { |
| 30 | + return []; |
| 31 | + } |
| 32 | + |
| 33 | + return array_map('strtolower', array_keys($envs)); |
| 34 | + } |
| 35 | + |
| 36 | + #[\Override] |
| 37 | + public function get($carrier, string $key): ?string |
| 38 | + { |
| 39 | + $value = getenv(strtoupper($key)); |
| 40 | + |
| 41 | + return is_string($value) ? $value : null; |
| 42 | + } |
| 43 | + |
| 44 | + #[\Override] |
| 45 | + public function getAll($carrier, string $key): array |
| 46 | + { |
| 47 | + $value = getenv(strtoupper($key)); |
| 48 | + |
| 49 | + return is_string($value) ? [$value] : []; |
| 50 | + } |
| 51 | + |
| 52 | + #[\Override] |
| 53 | + public function set(&$carrier, string $key, string $value): void |
| 54 | + { |
| 55 | + if ($key === '') { |
| 56 | + throw new InvalidArgumentException('Unable to set value with an empty key'); |
| 57 | + } |
| 58 | + |
| 59 | + putenv(sprintf('%s=%s', strtoupper($key), $value)); |
| 60 | + } |
| 61 | +} |
0 commit comments