Debian Codegraph @

lib/3rdParty/composer/spomky-labs/pki-framework/src/X509/Feature/DateTimeHelper.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace SpomkyLabs\Pki\X509\Feature;
6
7 use DateTimeImmutable;
8 use DateTimeZone;
9 use Exception;
10 use RuntimeException;
11 use UnexpectedValueException;
12
13 /**
14 * Helper trait for classes employing date and time handling.
15 */
16 trait DateTimeHelper
17 {
18 /**
19 * Create DateTime object from time string and timezone.
20 *
21 * @param null|string $time Time string, default to 'now'
22 * @param null|string $tz Timezone, default if omitted
23 */
24 private static function createDateTime(?string $time = null, ?string $tz = null): DateTimeImmutable
25 {
26 if (! isset($time)) {
27 $time = 'now';
28 }
29 if (! isset($tz)) {
30 $tz = date_default_timezone_get();
31 }
32 try {
33 $dt = new DateTimeImmutable($time, self::createTimeZone($tz));
34 return self::roundDownFractionalSeconds($dt);
35 } catch (Exception $e) {
36 throw new RuntimeException('Failed to create DateTime:', 0, $e);
37 }
38 }
39
40 /**
41 * Rounds a \DateTimeImmutable value such that fractional seconds are removed.
42 */
43 private static function roundDownFractionalSeconds(DateTimeImmutable $dt): DateTimeImmutable
44 {
45 return DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $dt->format('Y-m-d H:i:s'), $dt->getTimezone());
46 }
47
48 /**
49 * Create DateTimeZone object from string.
50 */
51 private static function createTimeZone(string $tz): DateTimeZone
52 {
53 try {
54 return new DateTimeZone($tz);
55 } catch (Exception $e) {
56 throw new UnexpectedValueException('Invalid timezone.', 0, $e);
57 }
58 }
59 }