1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of Badcow DNS Library. |
7
|
|
|
* |
8
|
|
|
* (c) Samuel Williams <[email protected]> |
9
|
|
|
* |
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Badcow\DNS\Parser; |
15
|
|
|
|
16
|
|
|
class TimeFormat |
17
|
|
|
{ |
18
|
|
|
public const TIME_FORMAT_REGEX = '/^(?:(\d+)w)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/i'; |
19
|
|
|
|
20
|
|
|
public const TIME_MULTIPLIERS = [ |
21
|
|
|
'w' => 604800, |
22
|
|
|
'd' => 86400, |
23
|
|
|
'h' => 3600, |
24
|
|
|
'm' => 60, |
25
|
|
|
's' => 1, |
26
|
|
|
]; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Check if given token looks like time format. |
30
|
|
|
* |
31
|
|
|
* @param string $value |
32
|
|
|
* |
33
|
|
|
* @return bool |
34
|
|
|
*/ |
35
|
26 |
|
public static function isTimeFormat($value): bool |
36
|
|
|
{ |
37
|
26 |
|
return \is_numeric($value) || 1 === \preg_match(self::TIME_FORMAT_REGEX, $value); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Convert human readable time format to seconds. |
42
|
|
|
* |
43
|
|
|
* @param string $value |
44
|
|
|
* |
45
|
|
|
* @return int |
46
|
|
|
*/ |
47
|
23 |
|
public static function toSeconds($value): int |
48
|
|
|
{ |
49
|
23 |
|
$seconds = 0; |
50
|
|
|
|
51
|
23 |
|
if (\is_numeric($value)) { |
52
|
23 |
|
$seconds = (int) $value; |
53
|
1 |
|
} elseif (1 === \preg_match(self::TIME_FORMAT_REGEX, $value, $matches)) { |
54
|
1 |
|
\array_shift($matches); |
55
|
|
|
$seconds = (int) \array_sum(\array_map(function ($fragment, $multiplier) { |
56
|
1 |
|
return (int) $fragment * $multiplier; |
57
|
1 |
|
}, $matches, self::TIME_MULTIPLIERS)); |
58
|
|
|
} |
59
|
|
|
|
60
|
23 |
|
return $seconds < 2 ** 31 ? $seconds : 0; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* Convert number of seconds to human readable format. |
65
|
|
|
* |
66
|
|
|
* @param int $seconds |
67
|
|
|
* |
68
|
|
|
* @return string |
69
|
|
|
*/ |
70
|
1 |
|
public static function toHumanReadable(int $seconds): string |
71
|
|
|
{ |
72
|
1 |
|
$humanReadable = ''; |
73
|
1 |
|
foreach (self::TIME_MULTIPLIERS as $suffix => $multiplier) { |
74
|
1 |
|
if ($seconds < $multiplier) { |
75
|
1 |
|
continue; |
76
|
|
|
} |
77
|
1 |
|
$current = \floor($seconds / $multiplier); |
78
|
1 |
|
if ($current > 0) { |
79
|
1 |
|
$humanReadable .= \sprintf('%d%s', $current, $suffix); |
80
|
1 |
|
$seconds -= ($current * $multiplier); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|
84
|
1 |
|
return $humanReadable; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|