Completed
Push — master ( 78dcf2...13bc52 )
by Sebastian
09:28
created

Time   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 0
dl 0
loc 50
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A timeSinceExecutionStart() 0 11 3
A formatTime() 0 13 5
1
<?php
2
namespace phpbu\App\Util;
3
4
use RuntimeException;
5
6
/**
7
 * Time utility class.
8
 *
9
 * @package    phpbu
10
 * @subpackage Util
11
 * @author     Sebastian Feldmann <[email protected]>
12
 * @copyright  Sebastian Feldmann <[email protected]>
13
 * @license    https://opensource.org/licenses/MIT The MIT License (MIT)
14
 * @link       http://phpbu.de/
15
 * @since      Class available since Release 5.1.2
16
 */
17
class Time
18
{
19
    /**
20
     * Time formatting helper
21
     *
22
     * @var array
23
     */
24
    private static $times = [
25
        'hour'   => 3600,
26
        'minute' => 60,
27
        'second' => 1
28
    ];
29
30
    /**
31
     * Returns the time passed since execution start.
32
     *
33
     * @throws \RuntimeException
34
     */
35 13
    public static function timeSinceExecutionStart() : float
36
    {
37 13
        if (isset($_SERVER['REQUEST_TIME_FLOAT'])) {
38 11
            $startOfRequest = $_SERVER['REQUEST_TIME_FLOAT'];
39 2
        } elseif (isset($_SERVER['REQUEST_TIME'])) {
40 1
            $startOfRequest = $_SERVER['REQUEST_TIME'];
41
        } else {
42 1
            throw new RuntimeException('Cannot determine time at which the execution started');
43
        }
44 12
        return \microtime(true) - $startOfRequest;
45
    }
46
47
    /**
48
     * Return string like '1 hour 3 minutes 12 seconds'.
49
     *
50
     * @param  float $time
51
     * @return string
52
     */
53 11
    public static function formatTime(float $time) : string
54
    {
55 11
        $time      = $time < 1 ? 1 : round($time);
56 11
        $formatted = [];
57 11
        foreach (self::$times as $unit => $value) {
58 11
            if ($time >= $value) {
59 11
                $units = \floor($time / $value);
60 11
                $time -= $units * $value;
61 11
                $formatted[] = $units . ' ' . ($units == 1 ? $unit : $unit . 's');
62
            }
63
        }
64 11
        return implode(' ', $formatted);
65
    }
66
}
67