-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathRelativeTimeFormatter.php
424 lines (378 loc) · 14.9 KB
/
RelativeTimeFormatter.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.2.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\I18n;
use Cake\Chronos\ChronosInterface;
use Cake\Chronos\DifferenceFormatterInterface;
/**
* Helper class for formatting relative dates & times.
*
* @internal
*/
class RelativeTimeFormatter implements DifferenceFormatterInterface
{
/**
* Get the difference in a human readable format.
*
* @param \Cake\Chronos\ChronosInterface $date The datetime to start with.
* @param \Cake\Chronos\ChronosInterface|null $other The datetime to compare against.
* @param bool $absolute Removes time difference modifiers ago, after, etc.
* @return string The difference between the two days in a human readable format.
* @see \Cake\Chronos\ChronosInterface::diffForHumans
*/
public function diffForHumans(
ChronosInterface $date,
?ChronosInterface $other = null,
bool $absolute = false
): string {
$isNow = $other === null;
if ($isNow) {
$other = $date->now($date->getTimezone());
}
/** @psalm-suppress PossiblyNullArgument */
$diffInterval = $date->diff($other);
switch (true) {
case $diffInterval->y > 0:
$count = $diffInterval->y;
$message = __dn('cake', '{0} year', '{0} years', $count, $count);
break;
case $diffInterval->m > 0:
$count = $diffInterval->m;
$message = __dn('cake', '{0} month', '{0} months', $count, $count);
break;
case $diffInterval->d > 0:
$count = $diffInterval->d;
if ($count >= I18nDateTimeInterface::DAYS_PER_WEEK) {
$count = (int)($count / I18nDateTimeInterface::DAYS_PER_WEEK);
$message = __dn('cake', '{0} week', '{0} weeks', $count, $count);
} else {
$message = __dn('cake', '{0} day', '{0} days', $count, $count);
}
break;
case $diffInterval->h > 0:
$count = $diffInterval->h;
$message = __dn('cake', '{0} hour', '{0} hours', $count, $count);
break;
case $diffInterval->i > 0:
$count = $diffInterval->i;
$message = __dn('cake', '{0} minute', '{0} minutes', $count, $count);
break;
default:
$count = $diffInterval->s;
$message = __dn('cake', '{0} second', '{0} seconds', $count, $count);
break;
}
if ($absolute) {
return $message;
}
$isFuture = $diffInterval->invert === 1;
if ($isNow) {
return $isFuture ? __d('cake', '{0} from now', $message) : __d('cake', '{0} ago', $message);
}
return $isFuture ? __d('cake', '{0} after', $message) : __d('cake', '{0} before', $message);
}
/**
* Format a into a relative timestring.
*
* @param \Cake\I18n\I18nDateTimeInterface $time The time instance to format.
* @param array $options Array of options.
* @return string Relative time string.
* @see \Cake\I18n\Time::timeAgoInWords()
*/
public function timeAgoInWords(I18nDateTimeInterface $time, array $options = []): string
{
$options = $this->_options($options, FrozenTime::class);
if ($options['timezone']) {
$time = $time->timezone($options['timezone']);
}
$now = $options['from']->format('U');
$inSeconds = $time->format('U');
$backwards = ($inSeconds > $now);
$futureTime = $now;
$pastTime = $inSeconds;
if ($backwards) {
$futureTime = $inSeconds;
$pastTime = $now;
}
$diff = $futureTime - $pastTime;
if (!$diff) {
return __d('cake', 'just now', 'just now');
}
if ($diff > abs($now - (new FrozenTime($options['end']))->format('U'))) {
return sprintf($options['absoluteString'], $time->i18nFormat($options['format']));
}
$diffData = $this->_diffData($futureTime, $pastTime, $backwards, $options);
[$fNum, $fWord, $years, $months, $weeks, $days, $hours, $minutes, $seconds] = array_values($diffData);
$relativeDate = [];
if ($fNum >= 1 && $years > 0) {
$relativeDate[] = __dn('cake', '{0} year', '{0} years', $years, $years);
}
if ($fNum >= 2 && $months > 0) {
$relativeDate[] = __dn('cake', '{0} month', '{0} months', $months, $months);
}
if ($fNum >= 3 && $weeks > 0) {
$relativeDate[] = __dn('cake', '{0} week', '{0} weeks', $weeks, $weeks);
}
if ($fNum >= 4 && $days > 0) {
$relativeDate[] = __dn('cake', '{0} day', '{0} days', $days, $days);
}
if ($fNum >= 5 && $hours > 0) {
$relativeDate[] = __dn('cake', '{0} hour', '{0} hours', $hours, $hours);
}
if ($fNum >= 6 && $minutes > 0) {
$relativeDate[] = __dn('cake', '{0} minute', '{0} minutes', $minutes, $minutes);
}
if ($fNum >= 7 && $seconds > 0) {
$relativeDate[] = __dn('cake', '{0} second', '{0} seconds', $seconds, $seconds);
}
$relativeDate = implode(', ', $relativeDate);
// When time has passed
if (!$backwards) {
$aboutAgo = [
'second' => __d('cake', 'about a second ago'),
'minute' => __d('cake', 'about a minute ago'),
'hour' => __d('cake', 'about an hour ago'),
'day' => __d('cake', 'about a day ago'),
'week' => __d('cake', 'about a week ago'),
'month' => __d('cake', 'about a month ago'),
'year' => __d('cake', 'about a year ago'),
];
return $relativeDate ? sprintf($options['relativeString'], $relativeDate) : $aboutAgo[$fWord];
}
// When time is to come
if ($relativeDate) {
return $relativeDate;
}
$aboutIn = [
'second' => __d('cake', 'in about a second'),
'minute' => __d('cake', 'in about a minute'),
'hour' => __d('cake', 'in about an hour'),
'day' => __d('cake', 'in about a day'),
'week' => __d('cake', 'in about a week'),
'month' => __d('cake', 'in about a month'),
'year' => __d('cake', 'in about a year'),
];
return $aboutIn[$fWord];
}
/**
* Calculate the data needed to format a relative difference string.
*
* @param int|string $futureTime The timestamp from the future.
* @param int|string $pastTime The timestamp from the past.
* @param bool $backwards Whether or not the difference was backwards.
* @param array $options An array of options.
* @return array An array of values.
*/
protected function _diffData($futureTime, $pastTime, bool $backwards, $options): array
{
$futureTime = (int)$futureTime;
$pastTime = (int)$pastTime;
$diff = $futureTime - $pastTime;
// If more than a week, then take into account the length of months
if ($diff >= 604800) {
$future = [];
[
$future['H'],
$future['i'],
$future['s'],
$future['d'],
$future['m'],
$future['Y'],
] = explode('/', date('H/i/s/d/m/Y', $futureTime));
$past = [];
[
$past['H'],
$past['i'],
$past['s'],
$past['d'],
$past['m'],
$past['Y'],
] = explode('/', date('H/i/s/d/m/Y', $pastTime));
$weeks = $days = $hours = $minutes = $seconds = 0;
$years = (int)$future['Y'] - (int)$past['Y'];
$months = (int)$future['m'] + (12 * $years) - (int)$past['m'];
if ($months >= 12) {
$years = floor($months / 12);
$months -= $years * 12;
}
if ((int)$future['m'] < (int)$past['m'] && (int)$future['Y'] - (int)$past['Y'] === 1) {
$years--;
}
if ((int)$future['d'] >= (int)$past['d']) {
$days = (int)$future['d'] - (int)$past['d'];
} else {
$daysInPastMonth = (int)date('t', $pastTime);
$daysInFutureMonth = (int)date('t', mktime(0, 0, 0, (int)$future['m'] - 1, 1, (int)$future['Y']));
if (!$backwards) {
$days = $daysInPastMonth - (int)$past['d'] + (int)$future['d'];
} else {
$days = $daysInFutureMonth - (int)$past['d'] + (int)$future['d'];
}
if ($future['m'] !== $past['m']) {
$months--;
}
}
if (!$months && $years >= 1 && $diff < $years * 31536000) {
$months = 11;
$years--;
}
if ($months >= 12) {
$years++;
$months -= 12;
}
if ($days >= 7) {
$weeks = floor($days / 7);
$days -= $weeks * 7;
}
} else {
$years = $months = $weeks = 0;
$days = floor($diff / 86400);
$diff -= $days * 86400;
$hours = floor($diff / 3600);
$diff -= $hours * 3600;
$minutes = floor($diff / 60);
$diff -= $minutes * 60;
$seconds = $diff;
}
$fWord = $options['accuracy']['second'];
if ($years > 0) {
$fWord = $options['accuracy']['year'];
} elseif (abs($months) > 0) {
$fWord = $options['accuracy']['month'];
} elseif (abs($weeks) > 0) {
$fWord = $options['accuracy']['week'];
} elseif (abs($days) > 0) {
$fWord = $options['accuracy']['day'];
} elseif (abs($hours) > 0) {
$fWord = $options['accuracy']['hour'];
} elseif (abs($minutes) > 0) {
$fWord = $options['accuracy']['minute'];
}
$fNum = str_replace(
['year', 'month', 'week', 'day', 'hour', 'minute', 'second'],
['1', '2', '3', '4', '5', '6', '7'],
$fWord
);
return [
$fNum,
$fWord,
(int)$years,
(int)$months,
(int)$weeks,
(int)$days,
(int)$hours,
(int)$minutes,
(int)$seconds,
];
}
/**
* Format a into a relative date string.
*
* @param \Cake\I18n\I18nDateTimeInterface $date The date to format.
* @param array $options Array of options.
* @return string Relative date string.
* @see \Cake\I18n\Date::timeAgoInWords()
*/
public function dateAgoInWords(I18nDateTimeInterface $date, array $options = []): string
{
$options = $this->_options($options, FrozenDate::class);
if ($options['timezone']) {
$date = $date->timezone($options['timezone']);
}
$now = $options['from']->format('U');
$inSeconds = $date->format('U');
$backwards = ($inSeconds > $now);
$futureTime = $now;
$pastTime = $inSeconds;
if ($backwards) {
$futureTime = $inSeconds;
$pastTime = $now;
}
$diff = $futureTime - $pastTime;
if (!$diff) {
return __d('cake', 'today');
}
if ($diff > abs($now - (new FrozenDate($options['end']))->format('U'))) {
return sprintf($options['absoluteString'], $date->i18nFormat($options['format']));
}
$diffData = $this->_diffData($futureTime, $pastTime, $backwards, $options);
[$fNum, $fWord, $years, $months, $weeks, $days] = array_values($diffData);
$relativeDate = [];
if ($fNum >= 1 && $years > 0) {
$relativeDate[] = __dn('cake', '{0} year', '{0} years', $years, $years);
}
if ($fNum >= 2 && $months > 0) {
$relativeDate[] = __dn('cake', '{0} month', '{0} months', $months, $months);
}
if ($fNum >= 3 && $weeks > 0) {
$relativeDate[] = __dn('cake', '{0} week', '{0} weeks', $weeks, $weeks);
}
if ($fNum >= 4 && $days > 0) {
$relativeDate[] = __dn('cake', '{0} day', '{0} days', $days, $days);
}
$relativeDate = implode(', ', $relativeDate);
// When time has passed
if (!$backwards) {
$aboutAgo = [
'day' => __d('cake', 'about a day ago'),
'week' => __d('cake', 'about a week ago'),
'month' => __d('cake', 'about a month ago'),
'year' => __d('cake', 'about a year ago'),
];
return $relativeDate ? sprintf($options['relativeString'], $relativeDate) : $aboutAgo[$fWord];
}
// When time is to come
if ($relativeDate) {
return $relativeDate;
}
$aboutIn = [
'day' => __d('cake', 'in about a day'),
'week' => __d('cake', 'in about a week'),
'month' => __d('cake', 'in about a month'),
'year' => __d('cake', 'in about a year'),
];
return $aboutIn[$fWord];
}
/**
* Build the options for relative date formatting.
*
* @param array $options The options provided by the user.
* @param string $class The class name to use for defaults.
* @return array Options with defaults applied.
* @psalm-param class-string<\Cake\I18n\FrozenDate>|class-string<\Cake\I18n\FrozenTime> $class
*/
protected function _options(array $options, string $class): array
{
$options += [
'from' => $class::now(),
'timezone' => null,
'format' => $class::$wordFormat,
'accuracy' => $class::$wordAccuracy,
'end' => $class::$wordEnd,
'relativeString' => __d('cake', '%s ago'),
'absoluteString' => __d('cake', 'on %s'),
];
if (is_string($options['accuracy'])) {
$accuracy = $options['accuracy'];
$options['accuracy'] = [];
foreach ($class::$wordAccuracy as $key => $level) {
$options['accuracy'][$key] = $accuracy;
}
} else {
$options['accuracy'] += $class::$wordAccuracy;
}
return $options;
}
}