<?php
 declare(strict_types=1); namespace SpomkyLabs\Pki\X509\Certificate; use DateTimeImmutable; use SpomkyLabs\Pki\ASN1\Element; use SpomkyLabs\Pki\ASN1\Type\Primitive\GeneralizedTime; use SpomkyLabs\Pki\ASN1\Type\Primitive\UTCTime; use SpomkyLabs\Pki\ASN1\Type\TimeType; use SpomkyLabs\Pki\X509\Feature\DateTimeHelper; use UnexpectedValueException; final class Time { use DateTimeHelper; private readonly int $type; private function __construct( protected DateTimeImmutable $dt, ?int $type ) { $this->type = $type ?? self::determineType($dt); } public static function create(DateTimeImmutable $dt, ?int $time = null): self { return new self($dt, $time); } public static function fromASN1(TimeType $el): self { if ($el instanceof UTCTime) { return self::create($el->dateTime(), Element::TYPE_UTC_TIME); } if ($el instanceof GeneralizedTime) { return self::create($el->dateTime(), Element::TYPE_GENERALIZED_TIME); } return self::create($el->dateTime()); } public static function fromString(?string $time, ?string $tz = null): self { return self::create(self::createDateTime($time, $tz)); } public function dateTime(): DateTimeImmutable { return $this->dt; } public function toASN1(): TimeType { $dt = $this->dt; switch ($this->type) { case Element::TYPE_UTC_TIME: return UTCTime::create($dt); case Element::TYPE_GENERALIZED_TIME: if ((int) $dt->format('u') !== 0) { $dt = self::roundDownFractionalSeconds($dt); } return GeneralizedTime::create($dt); } throw new UnexpectedValueException('Time type ' . Element::tagToName($this->type) . ' not supported.'); } protected static function determineType(DateTimeImmutable $dt): int { if ($dt->format('Y') >= 2050) { return Element::TYPE_GENERALIZED_TIME; } return Element::TYPE_UTC_TIME; } } 