1<?php
2/*
3 * This file is part of the PHPASN1 library.
4 *
5 * Copyright © Friedrich Große <friedrich.grosse@gmail.com>
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10
11namespace FG\ASN1\Universal;
12
13use FG\ASN1\AbstractTime;
14use FG\ASN1\Parsable;
15use FG\ASN1\Identifier;
16use FG\ASN1\Exception\ParserException;
17
18/**
19 * This ASN.1 universal type contains the calendar date and time.
20 *
21 * The precision is one minute or one second and optionally a
22 * local time differential from coordinated universal time.
23 *
24 * Decoding of this type will accept the Basic Encoding Rules (BER)
25 * The encoding will comply with the Distinguished Encoding Rules (DER).
26 */
27class UTCTime extends AbstractTime implements Parsable
28{
29    public function getType()
30    {
31        return Identifier::UTC_TIME;
32    }
33
34    protected function calculateContentLength()
35    {
36        return 13; // Content is a string o the following format: YYMMDDhhmmssZ (13 octets)
37    }
38
39    protected function getEncodedValue()
40    {
41        return $this->value->format('ymdHis').'Z';
42    }
43
44    public static function fromBinary(&$binaryData, &$offsetIndex = 0)
45    {
46        self::parseIdentifier($binaryData[$offsetIndex], Identifier::UTC_TIME, $offsetIndex++);
47        $contentLength = self::parseContentLength($binaryData, $offsetIndex, 11);
48
49        $format = 'ymdGi';
50        $dateTimeString = substr($binaryData, $offsetIndex, 10);
51        $offsetIndex += 10;
52
53        // extract optional seconds part
54        if ($binaryData[$offsetIndex] != 'Z'
55        && $binaryData[$offsetIndex] != '+'
56        && $binaryData[$offsetIndex] != '-') {
57            $dateTimeString .= substr($binaryData, $offsetIndex, 2);
58            $offsetIndex += 2;
59            $format .= 's';
60        }
61
62        $dateTime = \DateTime::createFromFormat($format, $dateTimeString, new \DateTimeZone('UTC'));
63
64        // extract time zone settings
65        if ($binaryData[$offsetIndex] == '+'
66        || $binaryData[$offsetIndex] == '-') {
67            $dateTime = static::extractTimeZoneData($binaryData, $offsetIndex, $dateTime);
68        } elseif ($binaryData[$offsetIndex++] != 'Z') {
69            throw new ParserException('Invalid UTC String', $offsetIndex);
70        }
71
72        $parsedObject = new self($dateTime);
73        $parsedObject->setContentLength($contentLength);
74
75        return $parsedObject;
76    }
77}
78