| 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 |
|
| 15 |
|
| 16 |
trait DateTimeHelper |
| 17 |
{ |
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 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 |
|
| 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 |
|
| 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 |
} |