44
55namespace OpenTelemetry \Context ;
66
7+ use function assert ;
78use function spl_object_id ;
89
910/**
1011 * @see https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/context/README.md#context
1112 */
12- final class Context
13+ final class Context implements ContextInterface
1314{
1415 /** @var ContextStorageInterface&ExecutionContextAwareInterface */
1516 private static ContextStorageInterface $ storage ;
1617
1718 // Optimization for spans to avoid copying the context array.
18- private static ContextKey $ spanContextKey ;
19+ private static ContextKeyInterface $ spanContextKey ;
1920 private ?object $ span = null ;
2021 /** @var array<int, mixed> */
2122 private array $ context = [];
22- /** @var array<int, ContextKey > */
23+ /** @var array<int, ContextKeyInterface > */
2324 private array $ contextKeys = [];
2425
2526 private function __construct ()
2627 {
2728 self ::$ spanContextKey = ContextKeys::span ();
2829 }
2930
30- public static function createKey (string $ key ): ContextKey
31+ public static function createKey (string $ key ): ContextKeyInterface
3132 {
3233 return new ContextKey ($ key );
3334 }
@@ -51,17 +52,29 @@ public static function storage(): ContextStorageInterface
5152 return self ::$ storage ??= new ContextStorage ();
5253 }
5354
55+ /**
56+ * @param ContextInterface|false|null $context
57+ *
58+ * @internal
59+ */
60+ public static function resolve ($ context , ?ContextStorageInterface $ contextStorage = null ): ContextInterface
61+ {
62+ return $ context
63+ ?? ($ contextStorage ?? self ::storage ())->current ()
64+ ?: self ::getRoot ();
65+ }
66+
5467 /**
5568 * @internal
5669 */
57- public static function getRoot (): Context
70+ public static function getRoot (): ContextInterface
5871 {
5972 static $ empty ;
6073
6174 return $ empty ??= new self ();
6275 }
6376
64- public static function getCurrent (): Context
77+ public static function getCurrent (): ContextInterface
6578 {
6679 return self ::storage ()->current ();
6780 }
@@ -75,12 +88,12 @@ public function activate(): ScopeInterface
7588 return $ scope ;
7689 }
7790
78- public function withContextValue (ImplicitContextKeyedInterface $ value ): Context
91+ public function withContextValue (ImplicitContextKeyedInterface $ value ): ContextInterface
7992 {
8093 return $ value ->storeInContext ($ this );
8194 }
8295
83- public function with (ContextKey $ key , $ value ): self
96+ public function with (ContextKeyInterface $ key , $ value ): self
8497 {
8598 if ($ this ->get ($ key ) === $ value ) {
8699 return $ this ;
@@ -108,9 +121,10 @@ public function with(ContextKey $key, $value): self
108121 return $ self ;
109122 }
110123
111- public function get (ContextKey $ key )
124+ public function get (ContextKeyInterface $ key )
112125 {
113126 if ($ key === self ::$ spanContextKey ) {
127+ /** @psalm-suppress InvalidReturnStatement */
114128 return $ this ->span ;
115129 }
116130
0 commit comments