FormatHelper   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 13
eloc 30
c 3
b 0
f 0
dl 0
loc 54
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B formatTime() 0 36 9
A formatDistance() 0 14 4
1
<?php
2
3
namespace DH\NavigationBundle\Helper;
4
5
class FormatHelper
6
{
7
    public static function formatTime(int $duration, int $precision = 1): string
8
    {
9
        static $formats = [
10
            [0, '< 1 sec'],
11
            [1, '1 sec'],
12
            [2, 'secs', 1],
13
            [60, '1 min'],
14
            [120, 'mins', 60],
15
            [3600, '1 hr'],
16
            [7200, 'hrs', 3600],
17
            [86400, '1 day'],
18
            [172800, 'days', 86400],
19
        ];
20
21
        foreach ($formats as $index => $format) {
22
            if ($duration >= $format[0]) {
23
                if ((isset($formats[$index + 1]) && $duration < $formats[$index + 1][0])
24
                    || $index === \count($formats) - 1
25
                ) {
26
                    if (2 === \count($format)) {
27
                        return $format[1];
28
                    }
29
30
                    --$precision;
31
32
                    $tmp = (int) floor($duration / $format[2]);
33
                    if (0 === $precision || 0 === $duration - ($tmp * $format[2])) {
34
                        return $tmp.' '.$format[1];
35
                    }
36
37
                    return $tmp.' '.$format[1].' '.self::formatTime($duration - ($tmp * $format[2]), $precision);
38
                }
39
            }
40
        }
41
42
        return '';
43
    }
44
45
    public static function formatDistance(int $distance, int $precision = 1): string
46
    {
47
        if ($distance < 1000) {
48
            return $distance.' m';
49
        }
50
51
        --$precision;
52
53
        $tmp = (int) floor($distance / 1000);
54
        if (0 === $precision || 0 === $distance - ($tmp * 1000)) {
55
            return round($distance / 1000, 1).' km';
56
        }
57
58
        return $tmp.' km '.self::formatDistance($distance - ($tmp * 1000), $precision);
59
    }
60
}
61