ServerTiming::measure()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace BeyondCode\ServerTiming;
4
5
use Symfony\Component\Stopwatch\Stopwatch;
6
7
class ServerTiming
8
{
9
    /** @var Stopwatch */
10
    protected $stopwatch;
11
12
    /** @var array */
13
    protected $finishedEvents = [];
14
15
    /** @var array */
16
    protected $startedEvents = [];
17
18
    public function __construct(Stopwatch $stopwatch)
19
    {
20
        $this->stopwatch = $stopwatch;
21
    }
22
23
    public function addMetric(string $metric)
24
    {
25
        $this->finishedEvents[$metric] = null;
26
27
        return $this;
28
    }
29
30
    public function hasStartedEvent(string $key): bool
31
    {
32
        return array_key_exists($key, $this->startedEvents);
33
    }
34
35
    public function measure(string $key)
36
    {
37
        if (! $this->hasStartedEvent($key)) {
38
            return $this->start($key);
39
        }
40
41
        return $this->stop($key);
42
    }
43
44
    public function start(string $key)
45
    {
46
        $this->stopwatch->start($key);
47
48
        $this->startedEvents[$key] = true;
49
50
        return $this;
51
    }
52
53
    public function stop(string $key)
54
    {
55
        if ($this->stopwatch->isStarted($key)) {
56
            $event = $this->stopwatch->stop($key);
57
58
            $this->setDuration($key, $event->getDuration());
59
60
            unset($this->startedEvents[$key]);
61
        }
62
63
        return $this;
64
    }
65
66
    public function stopAllUnfinishedEvents()
67
    {
68
        foreach (array_keys($this->startedEvents) as $startedEventName) {
69
            $this->stop($startedEventName);
70
        }
71
    }
72
73
    public function setDuration(string $key, $duration)
74
    {
75
        if (is_callable($duration)) {
76
            $this->start($key);
77
78
            call_user_func($duration);
79
80
            $this->stop($key);
81
        } else {
82
            $this->finishedEvents[$key] = $duration;
83
        }
84
85
        return $this;
86
    }
87
88
    public function getDuration(string $key)
89
    {
90
        return $this->finishedEvents[$key] ?? null;
91
    }
92
93
    public function events(): array
94
    {
95
        return $this->finishedEvents;
96
    }
97
98
}
99