DurationConverter::toHour()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace TK\API\Helper;
5
6
/**
7
 * Class DurationConverter
8
 * @package TK\API\Helper
9
 *
10
 * Converts ISO 8601 formatted duration
11
 */
12
class DurationConverter
13
{
14
    public const FORMAT_LONG = 'l';
15
    public const FORMAT_SHORT = 's';
16
17
    public static function getDateTimeParts(string $duration, $format) : array
18
    {
19
        if ($format === 'l') {
20
            preg_match('/^P(.*?)Y(.*?)M(.*?)DT(.*?)H(.*?)M(.*?)S$/', $duration, $matches);
21
            [, $year, $month, $day, $hour, $minute, $second] = array_map(function ($item) {
22
                return (float) $item;
23
            }, $matches);
24
            return [$year, $month, $day, $hour, $minute, $second];
25
        }
26
        preg_match('/^P(.*?)DT(.*?)H(.*?)M(.*?)S$/', $duration, $matches);
27
        [, $day, $hour, $minute, $second] = array_map(function ($item) {
28
            return (float) $item;
29
        }, $matches);
30
        return [0, 0, $day, $hour, $minute, $second];
31
    }
32
33
    public static function toSeconds(string $duration, ?string $format = 'l') : float
34
    {
35
        [$year, $month, $day, $hour, $minute, $second] = self::getDateTimeParts($duration, $format);
36
        $seconds = $year * 365 * 24 * 60 * 60
37
            + $month * 30 * 24 * 60 * 60
38
            + $day * 24 * 60 * 60
39
            + $hour * 60 * 60
40
            + $minute * 60
41
            + $second
42
        ;
43
        return $seconds;
44
    }
45
46
    public static function toMinute(string $duration, ?string $format = 'l') : float
47
    {
48
        return round(self::toSeconds($duration, $format) / 60, 2);
49
    }
50
51
    public static function toHour(string $duration, ?string $format = 'l') : float
52
    {
53
        return round(self::toMinute($duration, $format) / 60, 2);
54
    }
55
56
    public static function toDay(string $duration, ?string $format = 'l') : float
57
    {
58
        return round(self::toHour($duration, $format) / 24, 2);
59
    }
60
61
    public static function toMonth(string $duration, ?string $format = 'l') : float
62
    {
63
        return round(self::toDay($duration, $format) / 30, 1);
64
    }
65
66
    public static function toYear(string $duration, ?string $format = 'l') : float
67
    {
68
        return round(self::toDay($duration, $format) / 365, 1);
69
    }
70
}
71