|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace X509\Feature; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* Helper trait for classes employing date and time handling. |
|
7
|
|
|
*/ |
|
8
|
|
|
trait DateTimeHelper |
|
9
|
|
|
{ |
|
10
|
|
|
/** |
|
11
|
|
|
* Create DateTime object from time string and timezone. |
|
12
|
|
|
* |
|
13
|
|
|
* @param string|null $time Time string, default to 'now' |
|
14
|
|
|
* @param string|null $tz Timezone, default if omitted |
|
15
|
|
|
* @throws \RuntimeException |
|
16
|
|
|
* @return \DateTimeImmutable |
|
17
|
|
|
*/ |
|
18
|
|
|
private static function _createDateTime($time = null, $tz = null): \DateTimeImmutable |
|
19
|
|
|
{ |
|
20
|
|
|
try { |
|
21
|
|
|
if (!isset($tz)) { |
|
22
|
|
|
$tz = date_default_timezone_get(); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
$dt = new \DateTimeImmutable($time, self::_createTimeZone($tz)); |
|
26
|
|
|
return self::_roundDownFractionalSeconds($dt); |
|
27
|
|
|
} catch (\Exception $e) { |
|
28
|
|
|
throw new \RuntimeException( |
|
29
|
|
|
"Failed to create DateTime: " . |
|
30
|
|
|
self::_getLastDateTimeImmutableErrorsStr(), 0, $e); |
|
31
|
|
|
} |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Rounds a \DateTimeImmutable value such that fractional |
|
36
|
|
|
* seconds are removed. |
|
37
|
|
|
* |
|
38
|
|
|
* @param \DateTimeImmutable $dt |
|
39
|
|
|
* @return \DateTimeImmutable |
|
40
|
|
|
*/ |
|
41
|
|
|
private static function _roundDownFractionalSeconds(\DateTimeImmutable $dt): \DateTimeImmutable |
|
42
|
|
|
{ |
|
43
|
|
|
return \DateTimeImmutable::createFromFormat("Y-m-d H:i:s", |
|
44
|
|
|
$dt->format("Y-m-d H:i:s"), $dt->getTimezone()); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* Create DateTimeZone object from string. |
|
49
|
|
|
* |
|
50
|
|
|
* @param string $tz |
|
51
|
|
|
* @throws \UnexpectedValueException |
|
52
|
|
|
* @return \DateTimeZone |
|
53
|
|
|
*/ |
|
54
|
|
|
private static function _createTimeZone($tz) |
|
55
|
|
|
{ |
|
56
|
|
|
try { |
|
57
|
|
|
return new \DateTimeZone($tz); |
|
58
|
|
|
} catch (\Exception $e) { |
|
59
|
|
|
throw new \UnexpectedValueException("Invalid timezone.", 0, $e); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* Get last error caused by DateTimeImmutable. |
|
65
|
|
|
* |
|
66
|
|
|
* @return string |
|
67
|
|
|
*/ |
|
68
|
|
|
private static function _getLastDateTimeImmutableErrorsStr() |
|
69
|
|
|
{ |
|
70
|
|
|
$errors = \DateTimeImmutable::getLastErrors()["errors"]; |
|
71
|
|
|
return implode(", ", $errors); |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|