1 | <?php |
||
10 | trait NumericDateClaim |
||
11 | { |
||
12 | /** |
||
13 | * Constructor. |
||
14 | * |
||
15 | * @param int $timestamp Unix timestamp |
||
16 | */ |
||
17 | abstract public function __construct(int $timestamp); |
||
18 | |||
19 | /** |
||
20 | * Get the parameter value. |
||
21 | * |
||
22 | * @return string |
||
23 | */ |
||
24 | abstract public function value(); |
||
25 | |||
26 | /** |
||
27 | * Initialize instance from date/time string. |
||
28 | * |
||
29 | * @param string $time `strtotime` compatible time string |
||
30 | * @param string $tz Default timezone |
||
31 | * |
||
32 | * @throws \RuntimeException |
||
33 | * |
||
34 | * @return static |
||
35 | */ |
||
36 | 2 | public static function fromString(string $time, string $tz = 'UTC') |
|
37 | { |
||
38 | try { |
||
39 | 2 | $dt = new \DateTimeImmutable($time, self::_createTimeZone($tz)); |
|
40 | 1 | return new static($dt->getTimestamp()); |
|
41 | 1 | } catch (\Exception $e) { |
|
42 | 1 | throw new \RuntimeException( |
|
43 | 'Failed to create DateTime: ' . |
||
44 | 1 | self::_getLastDateTimeImmutableErrorsStr(), 0, $e); |
|
45 | } |
||
46 | } |
||
47 | |||
48 | /** |
||
49 | * Get date as a unix timestamp. |
||
50 | * |
||
51 | * @return int |
||
52 | */ |
||
53 | 1 | public function timestamp(): int |
|
54 | { |
||
55 | 1 | return (int) $this->value(); |
|
56 | } |
||
57 | |||
58 | /** |
||
59 | * Get date as a datetime object. |
||
60 | * |
||
61 | * @param string $tz Timezone |
||
62 | * |
||
63 | * @throws \RuntimeException |
||
64 | * |
||
65 | * @return \DateTimeImmutable |
||
66 | */ |
||
67 | 3 | public function dateTime(string $tz = 'UTC'): \DateTimeImmutable |
|
68 | { |
||
69 | 3 | $dt = \DateTimeImmutable::createFromFormat('!U', strval($this->value()), |
|
70 | 3 | self::_createTimeZone($tz)); |
|
71 | 2 | if (false === $dt) { |
|
72 | 1 | throw new \RuntimeException( |
|
73 | 'Failed to create DateTime: ' . |
||
74 | 1 | self::_getLastDateTimeImmutableErrorsStr()); |
|
75 | } |
||
76 | 1 | return $dt; |
|
77 | } |
||
78 | |||
79 | /** |
||
80 | * Create DateTimeZone object from string. |
||
81 | * |
||
82 | * @param string $tz |
||
83 | * |
||
84 | * @throws \UnexpectedValueException |
||
85 | * |
||
86 | * @return \DateTimeZone |
||
87 | */ |
||
88 | 5 | private static function _createTimeZone(string $tz): \DateTimeZone |
|
94 | } |
||
95 | } |
||
96 | |||
97 | /** |
||
98 | * Get last error caused by DateTimeImmutable. |
||
99 | * |
||
100 | * @return string |
||
101 | */ |
||
102 | 2 | private static function _getLastDateTimeImmutableErrorsStr(): string |
|
108 |