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