Skip to content

Commit 4d5d98f

Browse files
authored
feat(carreirs): implement environment context getter setter (#1668)
* feat(carreirs): implement environment context getter setter Closes #1566 * tests(carrier): add EnvironmentGetterSetter missing test * fix(carrier): modify keys empty env condition * test: use OpenTelemetry\Tests\TestState trait to handle environment * docs: add trace context and baggage environment carrier example * refactor: clean up baggage and trace context examples by removing unused span logic * test: fix Psalm static analysis failures
1 parent 0f2715e commit 4d5d98f

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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

Comments
 (0)