Skip to content

Commit 3a8c7cd

Browse files
Adds SMF\TimeInterval::localize() method
Signed-off-by: Jon Stovell <jonstovell@gmail.com>
1 parent 477bf3d commit 3a8c7cd

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

Sources/TimeInterval.php

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,71 @@ public function toParsable(): string
305305
return implode(' ', $result);
306306
}
307307

308+
/**
309+
* Formats the interval as a human-readable string in the current user's
310+
* language.
311+
*
312+
* @param array $format_chars Properties to include in the output.
313+
* Allowed values in this array: 'y', 'm', 'd', 'h', 'i', 's', 'f', 'a'.
314+
* Note that when 'f' is included, it will always be combined with 's' in
315+
* order to produce a single float value in the output.
316+
* @return string A human-readable string.
317+
*/
318+
public function localize(array $format_chars = ['y', 'm', 'd']): string
319+
{
320+
$result = [];
321+
322+
$txt_keys = [
323+
'y' => 'number_of_years',
324+
'm' => 'number_of_months',
325+
'd' => 'number_of_days',
326+
'a' => 'number_of_days',
327+
'h' => 'number_of_hours',
328+
'i' => 'number_of_minutes',
329+
's' => 'number_of_seconds',
330+
'f' => 'number_of_seconds',
331+
];
332+
333+
foreach ($format_chars as $c) {
334+
// Don't include a bunch of useless "0 <unit>" substrings.
335+
if (empty($this->{$c}) || !isset($txt_keys[$c])) {
336+
continue;
337+
}
338+
339+
switch ($c) {
340+
case 'f':
341+
if (!in_array('s', $format_chars)) {
342+
$result[] = Lang::getTxt($txt_keys[$c], [(float) $this->s + (float) $this->f]);
343+
}
344+
break;
345+
346+
case 's':
347+
if (in_array('f', $format_chars)) {
348+
$result[] = Lang::getTxt($txt_keys[$c], [(float) $this->s + (float) $this->f]);
349+
} else {
350+
$result[] = Lang::getTxt($txt_keys[$c], [$this->s]);
351+
}
352+
break;
353+
354+
default:
355+
$result[] = Lang::getTxt($txt_keys[$c], [$this->{$c}]);
356+
break;
357+
}
358+
}
359+
360+
// If all requested properties were empty, output a single "0 <unit>"
361+
// for the smallest unit requested.
362+
if (empty($result)) {
363+
foreach ($txt_keys as $c => $k) {
364+
if (in_array($c, $format_chars)) {
365+
$result = [Lang::getTxt($txt_keys[$c], [0])];
366+
}
367+
}
368+
}
369+
370+
return Lang::sentenceList($result);
371+
}
372+
308373
/**
309374
* Converts this interval to a number of seconds.
310375
*

0 commit comments

Comments
 (0)