Lines 0.00% 0 / 23
Methods 0.00% 0 / 11
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 __construct 0.00% 0 / 3 0.00% 0 / 1 6
 start 0.00% 0 / 1 0.00% 0 / 1 2
 stop 0.00% 0 / 1 0.00% 0 / 1 2
 pause 0.00% 0 / 2 0.00% 0 / 1 2
 resume 0.00% 0 / 1 0.00% 0 / 1 2
 getTime 0.00% 0 / 3 0.00% 0 / 1 6
 getLapTime 0.00% 0 / 1 0.00% 0 / 1 2
 getMicroTime 0.00% 0 / 2 0.00% 0 / 1 2
 timeToString 0.00% 0 / 6 0.00% 0 / 1 2
 roundMicroTime 0.00% 0 / 1 0.00% 0 / 1 2
 __destruct 0.00% 0 / 2 0.00% 0 / 1 6
7class Timer
8{
9    protected float $start;
10    protected float|null $pause = null;
11    protected float|null $stop = null;
12    protected float $elapsed = 0.0;
13
14    public function __construct()
15    {
16        $this->start();
17        if (true === DEBUG) {
18            fwrite(STDERR, 'Working - please wait...' . PHP_EOL);
19        }
20    }
21
22    public function start(): void
23    {
24        $this->start = Timer::getMicroTime();
25    }
26
27    /**
28     * @psalm-api
29     */
30    public function stop(): void
31    {
32        $this->stop = Timer::getMicroTime();
33    }
34
35    /**
36     * @psalm-api
37     */
38    public function pause(): void
39    {
40        $this->pause = Timer::getMicroTime();
41        $this->elapsed += ($this->pause - $this->start);
42    }
43
44    /**
45     * @psalm-api
46     */
47    public function resume(): void
48    {
49        $this->start = Timer::getMicroTime();
50    }
51
52    public function getTime(): string
53    {
54        if (!isset($this->stop)) {
55            $this->stop = Timer::getMicroTime();
56        }
57        return $this->timeToString();
58    }
59
60    /** @psalm-api */
61    protected function getLapTime(): string
62    {
63        return $this->timeToString();
64    }
65
66    protected static function getMicroTime(): float
67    {
68        list($usec, $sec) = explode(' ', microtime());
69        return ((float) $usec + (float) $sec);
70    }
71
72    protected function timeToString(): string
73    {
74        $seconds = ((float) ($this->stop ?? 0) - $this->start) + $this->elapsed;
75        $seconds = Timer::roundMicroTime($seconds);
76        $hours = floor($seconds / (60 * 60));
77        $divisorForMinutes = $seconds % (60 * 60);
78        $minutes = floor($divisorForMinutes / 60);
79        return $hours . "h:" . $minutes . "m:" . $seconds . "s";
80    }
81
82    protected static function roundMicroTime(mixed $microTime): float
83    {
84        return round($microTime, 4, PHP_ROUND_HALF_UP);
85    }
86
87    public function __destruct()
88    {
89        if (true === DEBUG) {
90            fwrite(STDERR, 'Job finished in ' . $this->getTime() . PHP_EOL);
91        }
92    }
93}