Completed
Pull Request — master (#24)
by
unknown
06:24 queued 03:07
created

DurationFormatter::formatDuration()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 23
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 20
nc 6
nop 1
dl 0
loc 23
rs 8.5906
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Chris dePage <[email protected]>
4
 * @copyright 2009-2018 Vanilla Forums Inc.
5
 * @license MIT
6
 */
7
8
namespace Garden\Cli\Logger\Formatter;
9
10
/**
11
 * Class DurationFormatter
12
 */
13
class DurationFormatter implements FormatterInterface {
14
15
    /**
16
     * Format one or more of the components of the log entry.
17
     *
18
     * @param int|string $time The time of the log entry.
19
     * @param string $logLevel The level of the message.
20
     * @param int $indentLevel The nesting level of the message.
21
     * @param string $message The message.
22
     * @param float|null|string $duration The duration to add to the message.
23
     *
24
     * @return array
25
     */
26
    public function format($time, string $logLevel, int $indentLevel, string $message, $duration) {
27
        $duration = $this->formatDuration($duration);
0 ignored issues
show
Bug introduced by
It seems like $duration can also be of type null and string; however, parameter $duration of Garden\Cli\Logger\Format...atter::formatDuration() does only seem to accept double, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

27
        $duration = $this->formatDuration(/** @scrutinizer ignore-type */ $duration);
Loading history...
28
29
        return [$time, $logLevel, $indentLevel, $message, $duration];
30
    }
31
32
    /**
33
     * Format a time duration.
34
     *
35
     * @param float $duration The duration in seconds and fractions of a second.
36
     *
37
     * @return string Returns the duration formatted for humans.
38
     */
39
    private function formatDuration(float $duration) {
40
        if ($duration < 1.0e-3) {
41
            $n = number_format($duration * 1.0e6, 0);
42
            $sx = 'μs';
43
        } elseif ($duration < 1) {
44
            $n = number_format($duration * 1000, 0);
45
            $sx = 'ms';
46
        } elseif ($duration < 60) {
47
            $n = number_format($duration, 1);
48
            $sx = 's';
49
        } elseif ($duration < 3600) {
50
            $n = number_format($duration / 60, 1);
51
            $sx = 'm';
52
        } elseif ($duration < 86400) {
53
            $n = number_format($duration / 3600, 1);
54
            $sx = 'h';
55
        } else {
56
            $n = number_format($duration / 86400, 1);
57
            $sx = 'd';
58
        }
59
60
        $result = rtrim($n, '0.').$sx;
61
        return $result;
62
    }
63
}
64