TimeKeeper   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 0
dl 0
loc 67
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A start() 0 8 2
A stop() 0 4 1
A elapsed() 0 8 3
A formatDuration() 0 16 5
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
13
     */
14
    protected $startedAt;
15
16
    /**
17
     * @var float
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
    /**
36
     * @return float|null
37
     */
38
    public function elapsed()
39
    {
40
        $finished = $this->finishedAt ? $this->finishedAt : microtime(true);
41
        if ($finished - $this->startedAt <= 0) {
42
            return null;
43
        }
44
        return $finished - $this->startedAt;
45
    }
46
47
    /**
48
     * Format a duration into a human-readable time.
49
     *
50
     * @param float $duration
51
     *   Duration in seconds, with fractional component.
52
     *
53
     * @return string
54
     */
55
    public static function formatDuration($duration)
56
    {
57
        if ($duration >= self::DAY * 2) {
58
            return gmdate('z \d\a\y\s H:i:s', $duration);
59
        }
60
        if ($duration > self::DAY) {
61
            return gmdate('\1 \d\a\y H:i:s', $duration);
62
        }
63
        if ($duration > self::HOUR) {
64
            return gmdate("H:i:s", $duration);
65
        }
66
        if ($duration > self::MINUTE) {
67
            return gmdate("i:s", $duration);
68
        }
69
        return round($duration, 3) . 's';
70
    }
71
}
72