forked from KnpLabs/KnpTimeBundle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDateTimeFormatter.php
99 lines (84 loc) · 2.69 KB
/
DateTimeFormatter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
namespace Knp\Bundle\TimeBundle;
use Symfony\Component\Translation\TranslatorInterface;
use DatetimeInterface;
class DateTimeFormatter
{
protected $translator;
/**
* Constructor
*
* @param TranslatorInterface $translator Translator used for messages
*/
public function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
}
/**
* Returns a formatted diff for the given from and to datetimes
*
* @param DateTimeInterface $from
* @param DateTimeInterface $to
*
* @return string
*/
public function formatDiff(DateTimeInterface $from, DateTimeInterface $to)
{
static $units = array(
'y' => 'year',
'm' => 'month',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second'
);
$diff = $to->diff($from);
foreach ($units as $attribute => $unit) {
$count = $diff->$attribute;
if (0 !== $count) {
return $this->doGetDiffMessage($count, $diff->invert, $unit);
}
}
return $this->getEmptyDiffMessage();
}
/**
* Returns the diff message for the specified count and unit
*
* @param integer $count The diff count
* @param boolean $invert Whether to invert the count
* @param integer $unit The unit must be either year, month, day, hour,
* minute or second
*
* @return string
*/
public function getDiffMessage($count, $invert, $unit)
{
if (0 === $count) {
throw new \InvalidArgumentException('The count must not be null.');
}
$unit = strtolower($unit);
if (!in_array($unit, array('year', 'month', 'day', 'hour', 'minute', 'second'))) {
throw new \InvalidArgumentException(sprintf('The unit \'%s\' is not supported.', $unit));
}
return $this->doGetDiffMessage($count, $invert, $unit);
}
protected function doGetDiffMessage($count, $invert, $unit)
{
$id = sprintf('diff.%s.%s', $invert ? 'ago' : 'in', $unit);
// check for Symfony >= 4.2
if (class_exists('Symfony\Component\Translation\Formatter\IntlFormatter')) {
return $this->translator->trans($id, array('%count%' => $count), 'time');
} else {
return $this->translator->transChoice($id, $count, array('%count%' => $count), 'time');
}
}
/**
* Returns the message for an empty diff
*
* @return string
*/
public function getEmptyDiffMessage()
{
return $this->translator->trans('diff.empty', array(), 'time');
}
}