Tracer::getActiveSpan()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 3
nc 2
nop 0
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 3
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace OpenTelemetry\Tracing;
6
7
class Tracer
8
{
9
    private $active;
10
    private $spans = [];
11
    private $tail = [];
12
13 12
    public function __construct(SpanContext $context = null)
14
    {
15 12
        $context = $context ?: SpanContext::generate();
16 12
        $this->active = $this->generateSpanInstance('tracer', $context);
17 12
    }
18
19 12
    public function getActiveSpan(): Span
20
    {
21 12
        while (count($this->tail) && $this->active->getEnd()) {
22 3
            $this->active = array_pop($this->tail);
23
        }
24 12
        return $this->active;
25
    }
26
27 9
    public function setActive(Span $span): Span
28
    {
29 9
        $this->tail[] = $this->active;
30 9
        return $this->active = $span;
31
    }
32
33 9
    public function createSpan(string $name): Span
34
    {
35 9
        $parent = $this->getActiveSpan()->getSpanContext();
36 9
        $context = SpanContext::fork($parent->getTraceId());
37 9
        $span = $this->generateSpanInstance($name, $context);
38 9
        return $this->setActive($span);
39
    }
40
41 2
    public function getSpans(): array
42
    {
43 2
        return $this->spans;
44
    }
45
46 12
    private function generateSpanInstance($name, SpanContext $context): Span
47
    {
48 12
        $parent = null;
49 12
        if ($this->active) {
50 9
            $parent = $this->getActiveSpan()->getSpanContext();
51
        }
52 12
        $span = new Span($name, $context, $parent);
53 12
        $this->spans[] = $span;
54 12
        return $span;
55
    }
56
}
57