Debian Codegraph @

vendor/ipl/web/src/Widget/TimeAgo.php

raw
1 <?php
2
3 namespace ipl\Web\Widget;
4
5 use DateTime;
6 use Exception;
7 use ipl\Html\Attributes;
8 use ipl\I18n\Translation;
9
10 class TimeAgo extends Time
11 {
12 protected $defaultAttributes = ['class' => 'time-ago', 'data-relative-time' => 'ago'];
13
14 /**
15 * @param int|float|DateTime|null $time Time as timestamp, DateTime object, or null for current time
16 * @param ?DateTime $compareTime Time to compare with, null for current time
17 *
18 * @throws Exception
19 */
20 public function __construct(int|float|DateTime|null $time = null, ?DateTime $compareTime = null)
21 {
22 $this->compareTime = $compareTime;
23
24 if (! $time instanceof DateTime) {
25 $time = $this->castToDateTime($time);
26 }
27
28 parent::__construct($time);
29 }
30
31 protected function format(): string
32 {
33 [$time, $type, $interval] = $this->diff($this->compareTime);
34
35 return sprintf(
36 match ($type) {
37 self::RELATIVE => $this->translate('%s ago', 'An event that happened the given time interval ago'),
38 self::TIME => $this->translate('at %s', 'An event happened at the given time'),
39 self::DATE => $this->translate('on %s', 'An event happened on the given date or date and time'),
40 },
41 $time
42 );
43 }
44 }