Stopwatch   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 78
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 78
ccs 23
cts 23
cp 1
rs 10
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A start() 0 13 3
A getDuration() 0 7 2
A stop() 0 7 2
A __construct() 0 4 1
A now() 0 3 1
1
<?php
2
3
namespace ZoiloMora\ElasticAPM\Helper\Stopwatch;
4
5
use ZoiloMora\ElasticAPM\Helper\Stopwatch\Exception\AlreadyRunningException;
6
use ZoiloMora\ElasticAPM\Helper\Stopwatch\Exception\NotStartedException;
7
use ZoiloMora\ElasticAPM\Helper\Stopwatch\Exception\NotStoppedException;
8
9
final class Stopwatch
10
{
11
    /**
12
     * @var double|null
13
     */
14
    private $startedOn;
15
16
    /**
17
     * @var double|null
18
     */
19
    private $stoppedOn;
20
21 24
    public function __construct()
22
    {
23 24
        $this->startedOn = null;
24 24
        $this->startedOn = null;
25 24
    }
26
27
    /**
28
     * @param double|null $startedOn
29
     *
30
     * @return void
31
     *
32
     * @throws AlreadyRunningException
33
     */
34 23
    public function start($startedOn = null)
35
    {
36 23
        if (null !== $this->startedOn) {
37 1
            throw AlreadyRunningException::create();
38
        }
39
40 23
        if (null !== $startedOn) {
41 19
            $this->startedOn = $startedOn;
42
43 19
            return;
44
        }
45
46 4
        $this->startedOn = $this->now();
47 4
    }
48
49
    /**
50
     * @return void
51
     *
52
     * @throws NotStartedException
53
     */
54 10
    public function stop()
55
    {
56 10
        if (null === $this->startedOn) {
57 1
            throw NotStartedException::create();
58
        }
59
60 9
        $this->stoppedOn = $this->now();
61 9
    }
62
63
    /**
64
     * Get current datetime in MicroSeconds
65
     *
66
     * @return int
67
     */
68 12
    private function now()
69
    {
70 12
        return (int) (microtime(true) * 1000000);
71
    }
72
73
    /**
74
     * Get the Duration in MilliSeconds
75
     *
76
     * @return double
77
     *
78
     * @throws NotStoppedException
79
     */
80 10
    public function getDuration()
81
    {
82 10
        if (null === $this->stoppedOn) {
83 1
            throw NotStoppedException::create();
84
        }
85
86 9
        return ($this->stoppedOn - $this->startedOn) / 1000;
87
    }
88
}
89