1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Win\Calendar; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Formata data para Humano |
7
|
|
|
*/ |
8
|
|
|
class TimeAgo extends DateFormat { |
9
|
|
|
|
10
|
|
|
/** @var string[] Nome das unidades de tempo */ |
11
|
|
|
static private $unitsName = array( |
12
|
|
|
'seconds' => ['segundo', 'segundos'], |
13
|
|
|
'minutes' => ['minuto', 'minutos'], |
14
|
|
|
'hours' => ['hora', 'horas'], |
15
|
|
|
'days' => ['dia', 'dias'], |
16
|
|
|
'weeks' => ['semana', 'semanas'], |
17
|
|
|
'months' => ['mês', 'mêses'], |
18
|
|
|
'years' => ['ano', 'anos'] |
19
|
|
|
); |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Retorna a data no formato humano |
23
|
|
|
* @return string (ex: 4 horas atrás), (ex: daqui a 5 dias) |
24
|
|
|
*/ |
25
|
|
|
public static function format(Date $date) { |
26
|
|
|
if ($date->isEmpty()) { |
27
|
|
|
return 'indisponível'; |
28
|
|
|
} |
29
|
|
|
$time = time() - strtotime($date->format('d-m-y h:i:s')); |
30
|
|
|
|
31
|
|
|
if ($time == 0) { |
32
|
|
|
return 'agora mesmo'; |
33
|
|
|
} |
34
|
|
|
if ($time > 0) { |
35
|
|
|
return static::getTime($time) . ' atrás'; |
36
|
|
|
} |
37
|
|
|
if ($time < 0) { |
38
|
|
|
return 'daqui a ' . static::getTime($time * (-1)); |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Retorna a data em unidade de tempo Humana |
44
|
|
|
* @param int $seconds |
45
|
|
|
* @return string Ex: 15 horas |
46
|
|
|
*/ |
47
|
|
|
protected static function getTime($seconds) { |
48
|
|
|
$units = array_reverse(Date::$units); |
49
|
|
|
foreach ($units as $unitName => $unitTotal) { |
50
|
|
|
if ($seconds > $unitTotal) { |
51
|
|
|
$timeTotal = floor($seconds / $unitTotal); |
52
|
|
|
$isPlural = ($timeTotal > 1); |
53
|
|
|
return $timeTotal . ' ' . static::$unitsName[$unitName][$isPlural]; |
|
|
|
|
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
return 0; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
} |
60
|
|
|
|
Let’s assume you have a class which uses late-static binding:
The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the
getSomeVariable()
on that sub-class, you will receive a runtime error:In the case above, it makes sense to update
SomeClass
to useself
instead: