1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Sop\ASN1\Type\Primitive; |
6
|
|
|
|
7
|
|
|
use Sop\ASN1\Component\Identifier; |
8
|
|
|
use Sop\ASN1\Component\Length; |
9
|
|
|
use Sop\ASN1\Exception\DecodeException; |
10
|
|
|
use Sop\ASN1\Feature\ElementBase; |
11
|
|
|
use Sop\ASN1\Type\PrimitiveType; |
12
|
|
|
use Sop\ASN1\Type\TimeType; |
13
|
|
|
use Sop\ASN1\Type\UniversalClass; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Implements *UTCTime* type. |
17
|
|
|
*/ |
18
|
|
|
class UTCTime extends TimeType |
19
|
|
|
{ |
20
|
|
|
use UniversalClass; |
21
|
|
|
use PrimitiveType; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Regular expression to parse date. |
25
|
|
|
* |
26
|
|
|
* DER restricts format to UTC timezone (Z suffix). |
27
|
|
|
* |
28
|
|
|
* @var string |
29
|
|
|
*/ |
30
|
|
|
const REGEX = '#^' . |
31
|
|
|
'(\d\d)' . // YY |
32
|
|
|
'(\d\d)' . // MM |
33
|
|
|
'(\d\d)' . // DD |
34
|
|
|
'(\d\d)' . // hh |
35
|
|
|
'(\d\d)' . // mm |
36
|
|
|
'(\d\d)' . // ss |
37
|
|
|
'Z' . // TZ |
38
|
|
|
'$#'; |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Constructor. |
42
|
|
|
* |
43
|
|
|
* @param \DateTimeImmutable $dt |
44
|
|
|
*/ |
45
|
8 |
|
public function __construct(\DateTimeImmutable $dt) |
46
|
|
|
{ |
47
|
8 |
|
$this->_typeTag = self::TYPE_UTC_TIME; |
48
|
8 |
|
parent::__construct($dt); |
49
|
8 |
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* {@inheritdoc} |
53
|
|
|
*/ |
54
|
2 |
|
protected function _encodedContentDER(): string |
55
|
|
|
{ |
56
|
2 |
|
$dt = $this->_dateTime->setTimezone(self::_createTimeZone(self::TZ_UTC)); |
57
|
2 |
|
return $dt->format('ymdHis\\Z'); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* {@inheritdoc} |
62
|
|
|
*/ |
63
|
11 |
|
protected static function _decodeFromDER(Identifier $identifier, |
64
|
|
|
string $data, int &$offset): ElementBase |
65
|
|
|
{ |
66
|
11 |
|
$idx = $offset; |
67
|
11 |
|
$length = Length::expectFromDER($data, $idx)->intLength(); |
68
|
11 |
|
$str = substr($data, $idx, $length); |
69
|
11 |
|
$idx += $length; |
70
|
|
|
/** @var string[] $match */ |
71
|
11 |
|
if (!preg_match(self::REGEX, $str, $match)) { |
72
|
5 |
|
throw new DecodeException('Invalid UTCTime format.'); |
73
|
|
|
} |
74
|
6 |
|
[, $year, $month, $day, $hour, $minute, $second] = $match; |
75
|
6 |
|
$time = $year . $month . $day . $hour . $minute . $second . self::TZ_UTC; |
76
|
6 |
|
$dt = \DateTimeImmutable::createFromFormat('!ymdHisT', $time, |
77
|
6 |
|
self::_createTimeZone(self::TZ_UTC)); |
78
|
6 |
|
if (!$dt) { |
79
|
|
|
throw new DecodeException( |
80
|
|
|
'Failed to decode UTCTime: ' . |
81
|
|
|
self::_getLastDateTimeImmutableErrorsStr()); |
82
|
|
|
} |
83
|
6 |
|
$offset = $idx; |
84
|
6 |
|
return new self($dt); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|