Completed
Pull Request — master (#997)
by Andrzej
02:14
created

TimeKeeper::start()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
namespace Robo\Common;
4
5
class TimeKeeper
6
{
7
    const MINUTE = 60;
8
    const HOUR = 3600;
9
    const DAY = 86400;
10
11
    /**
12
     * @var float|null
13
     */
14
    protected $startedAt;
15
16
    /**
17
     * @var float|null
18
     */
19
    protected $finishedAt;
20
21
    public function start()
22
    {
23
        if ($this->startedAt) {
24
            return;
25
        }
26
        // Get time in seconds as a float, accurate to the microsecond.
27
        $this->startedAt = microtime(true);
28
    }
29
30
    public function stop()
31
    {
32
        $this->finishedAt = microtime(true);
33
    }
34
35
    public function reset()
36
    {
37
        $this->startedAt = $this->finishedAt = null;
38
    }
39
40
    /**
41
     * @return float|null
42
     */
43
    public function elapsed()
44
    {
45
        $finished = $this->finishedAt ? $this->finishedAt : microtime(true);
46
        if ($finished - $this->startedAt <= 0) {
47
            return null;
48
        }
49
        return $finished - $this->startedAt;
50
    }
51
52
    /**
53
     * Format a duration into a human-readable time.
54
     *
55
     * @param float $duration
56
     *   Duration in seconds, with fractional component.
57
     *
58
     * @return string
59
     */
60
    public static function formatDuration($duration)
61
    {
62
        if ($duration >= self::DAY * 2) {
63
            return gmdate('z \d\a\y\s H:i:s', $duration);
64
        }
65
        if ($duration > self::DAY) {
66
            return gmdate('\1 \d\a\y H:i:s', $duration);
67
        }
68
        if ($duration > self::HOUR) {
69
            return gmdate("H:i:s", $duration);
70
        }
71
        if ($duration > self::MINUTE) {
72
            return gmdate("i:s", $duration);
73
        }
74
        return round($duration, 3) . 's';
75
    }
76
}
77