Debian Codegraph @

lib/3rdParty/composer/spomky-labs/pki-framework/src/X509/Certificate/Time.php

raw symbols SCIP
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 * Implements *Time* ASN.1 type.
17 *
18 * @see https://tools.ietf.org/html/rfc5280#section-4.1
19 */
20 final class Time
21 {
22 use DateTimeHelper;
23
24 /**
25 * Time ASN.1 type tag.
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 * Initialize from ASN.1.
43 */
44 public static function fromASN1(TimeType $el): self
45 {
46 // Pass the type of the original ASN.1 primitive
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()); // TODO: should never happen?
55 }
56
57 /**
58 * Initialize from date string.
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 * Generate ASN.1.
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 // GeneralizedTime must not contain fractional seconds
81 // (rfc5280 4.1.2.5.2)
82 if ((int) $dt->format('u') !== 0) {
83 // remove fractional seconds (round down)
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 * Determine whether to use UTCTime or GeneralizedTime ASN.1 type.
93 *
94 * @return int Type tag
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 }