Completed
Push — master ( a7b0c2...fe24f6 )
by Wanderson
02:20
created

TimeAgo::format()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 5
nop 1
dl 0
loc 16
rs 8.8571
c 0
b 0
f 0
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];
0 ignored issues
show
Bug introduced by
Since $unitsName is declared private, accessing it with static will lead to errors in possible sub-classes; consider using self, or increasing the visibility of $unitsName to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return static::$someVariable;
    }
}

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:

class YourSubClass extends YourClass { }

YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class SomeClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return self::$someVariable; // self works fine with private.
    }
}
Loading history...
54
			}
55
		}
56
		return 0;
57
	}
58
59
}
60