| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace SpomkyLabs\Pki\X509\Certificate; |
| 6 |
|
| 7 |
use DateTimeImmutable; |
| 8 |
use SpomkyLabs\Pki\ASN1\Element; |
| 9 |
use SpomkyLabs\Pki\ASN1\Type\Primitive\GeneralizedTime; |
| 10 |
use SpomkyLabs\Pki\ASN1\Type\Primitive\UTCTime; |
| 11 |
use SpomkyLabs\Pki\ASN1\Type\TimeType; |
| 12 |
use SpomkyLabs\Pki\X509\Feature\DateTimeHelper; |
| 13 |
use UnexpectedValueException; |
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
final class Time |
| 21 |
{ |
| 22 |
use DateTimeHelper; |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
private readonly int $type; |
| 28 |
|
| 29 |
private function __construct( |
| 30 |
protected DateTimeImmutable $dt, |
| 31 |
?int $type |
| 32 |
) { |
| 33 |
$this->type = $type ?? self::determineType($dt); |
| 34 |
} |
| 35 |
|
| 36 |
public static function create(DateTimeImmutable $dt, ?int $time = null): self |
| 37 |
{ |
| 38 |
return new self($dt, $time); |
| 39 |
} |
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
public static function fromASN1(TimeType $el): self |
| 45 |
{ |
| 46 |
|
| 47 |
if ($el instanceof UTCTime) { |
| 48 |
return self::create($el->dateTime(), Element::TYPE_UTC_TIME); |
| 49 |
} |
| 50 |
if ($el instanceof GeneralizedTime) { |
| 51 |
return self::create($el->dateTime(), Element::TYPE_GENERALIZED_TIME); |
| 52 |
} |
| 53 |
|
| 54 |
return self::create($el->dateTime()); |
| 55 |
} |
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
public static function fromString(?string $time, ?string $tz = null): self |
| 61 |
{ |
| 62 |
return self::create(self::createDateTime($time, $tz)); |
| 63 |
} |
| 64 |
|
| 65 |
public function dateTime(): DateTimeImmutable |
| 66 |
{ |
| 67 |
return $this->dt; |
| 68 |
} |
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
public function toASN1(): TimeType |
| 74 |
{ |
| 75 |
$dt = $this->dt; |
| 76 |
switch ($this->type) { |
| 77 |
case Element::TYPE_UTC_TIME: |
| 78 |
return UTCTime::create($dt); |
| 79 |
case Element::TYPE_GENERALIZED_TIME: |
| 80 |
|
| 81 |
|
| 82 |
if ((int) $dt->format('u') !== 0) { |
| 83 |
|
| 84 |
$dt = self::roundDownFractionalSeconds($dt); |
| 85 |
} |
| 86 |
return GeneralizedTime::create($dt); |
| 87 |
} |
| 88 |
throw new UnexpectedValueException('Time type ' . Element::tagToName($this->type) . ' not supported.'); |
| 89 |
} |
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
protected static function determineType(DateTimeImmutable $dt): int |
| 97 |
{ |
| 98 |
if ($dt->format('Y') >= 2050) { |
| 99 |
return Element::TYPE_GENERALIZED_TIME; |
| 100 |
} |
| 101 |
return Element::TYPE_UTC_TIME; |
| 102 |
} |
| 103 |
} |