Debian Codegraph @

vendor/ipl/web/src/Widget/TimeUntil.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 TimeUntil extends Time
11 {
12 protected $defaultAttributes = ['class' => 'time-until', 'data-relative-time' => 'until'];
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 if ($interval->days === 0 && $interval->h === 0) {
36 $this->addAttributes(
37 Attributes::create(
38 [
39 'data-ago-label' => sprintf(
40 $this->translate('%s ago', 'An event that happened the given time interval ago'),
41 '0m 0s'
42 )
43 ]
44 )
45 );
46 }
47
48 if (
49 $interval->invert !== 1 && $type === static::RELATIVE
50 && ($interval->days !== 0 || $interval->h !== 0 || $interval->i !== 0 || $interval->s !== 0)
51 ) {
52 $time = '-' . $time;
53 }
54
55 return sprintf(
56 match ($type) {
57 self::RELATIVE => $this->translate(
58 'in %s',
59 'An event will happen after the given time interval has elapsed'
60 ),
61 self::TIME => $this->translate('at %s', 'An event will happen at the given time'),
62 self::DATE => $this->translate('on %s', 'An event will happen on the given date or date and time'),
63 },
64 $time
65 );
66 }
67 }