summaryrefslogtreecommitdiff
path: root/vendor/open-telemetry/context/FiberBoundContextStorage.php
blob: 667f73b3d23c6d5137b71c39a5efdd0939785263 (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
<?php

/** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */

declare(strict_types=1);

namespace OpenTelemetry\Context;

use function assert;
use function class_exists;
use const E_USER_WARNING;
use Fiber;
use function trigger_error;

/**
 * @internal
 *
 * @phan-file-suppress PhanUndeclaredClassReference
 * @phan-file-suppress PhanUndeclaredClassMethod
 */
final class FiberBoundContextStorage implements ContextStorageInterface, ExecutionContextAwareInterface
{
    /** @var ContextStorageInterface&ExecutionContextAwareInterface */
    private ContextStorageInterface $storage;

    /**
     * @param ContextStorageInterface&ExecutionContextAwareInterface $storage
     */
    public function __construct(ContextStorageInterface $storage)
    {
        $this->storage = $storage;
    }

    public function fork($id): void
    {
        $this->storage->fork($id);
    }

    public function switch($id): void
    {
        $this->storage->switch($id);
    }

    public function destroy($id): void
    {
        $this->storage->destroy($id);
    }

    public function scope(): ?ContextStorageScopeInterface
    {
        $this->checkFiberMismatch();

        if (($scope = $this->storage->scope()) === null) {
            return null;
        }

        return new FiberBoundContextStorageScope($scope);
    }

    public function current(): ContextInterface
    {
        $this->checkFiberMismatch();

        return $this->storage->current();
    }

    public function attach(ContextInterface $context): ContextStorageScopeInterface
    {
        $scope = $this->storage->attach($context);
        assert(class_exists(Fiber::class, false));
        $scope[Fiber::class] = Fiber::getCurrent();

        return new FiberBoundContextStorageScope($scope);
    }

    private function checkFiberMismatch(): void
    {
        $scope = $this->storage->scope();
        assert(class_exists(Fiber::class, false));
        if ($scope && $scope[Fiber::class] !== Fiber::getCurrent()) {
            trigger_error('Fiber context switching not supported', E_USER_WARNING);
        }
    }
}