1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
|
4
|
|
|
namespace Ayesh\PHP_Timer; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* Class Formmater |
8
|
|
|
* Formatter helper to format time intervals. |
9
|
|
|
* @internal |
10
|
|
|
* @package Ayesh\PHP_Timer |
11
|
|
|
*/ |
12
|
|
|
class Formatter { |
13
|
|
|
|
14
|
|
|
private function __construct() { |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
public static function formatTime(int $miliseconds): string { |
18
|
|
|
$units = [ // Do not reorder the array order. |
19
|
|
|
31536000000 => ['1 year', '@count years'], |
20
|
|
|
2592000000 => ['1 month', '@count months'], |
21
|
|
|
604800000 => ['1 week', '@count weeks'], |
22
|
|
|
86400000 => ['1 day', '@count days'], |
23
|
|
|
3600000 => ['1 hour', '@count hours'], |
24
|
|
|
60000 => ['1 min', '@count min'], |
25
|
|
|
1000 => ['1 sec', '@count sec'], |
26
|
|
|
1 => ['1 ms', '@count ms'], |
27
|
|
|
]; |
28
|
|
|
|
29
|
|
|
$granularity = 2; |
30
|
|
|
$output = []; |
31
|
|
|
foreach ($units as $value => $string_pair) { |
32
|
|
|
if ($miliseconds >= $value) { |
33
|
|
|
$output[] = static::formatPlural((int) floor($miliseconds / $value), $string_pair[0], $string_pair[1]); |
34
|
|
|
$miliseconds %= $value; |
35
|
|
|
$granularity--; |
36
|
|
|
} |
37
|
|
|
if ($granularity === 0) { |
38
|
|
|
break; |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
return $output ? implode(' ', $output) : '0 sec'; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
protected static function formatPlural(int $count, string $singular, string $plural, array $args = array()): string { |
46
|
|
|
$args['@count'] = $count; |
47
|
|
|
return $count === 1 |
48
|
|
|
? strtr($singular, $args) |
49
|
|
|
: strtr($plural, $args); |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|