AbstractTime.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. namespace FG\ASN1;
  11. use DateInterval;
  12. use DateTime;
  13. use DateTimeZone;
  14. use Exception;
  15. abstract class AbstractTime extends ASNObject
  16. {
  17. /** @var DateTime */
  18. protected $value;
  19. public function __construct($dateTime = null, $dateTimeZone = 'UTC')
  20. {
  21. if ($dateTime == null || is_string($dateTime)) {
  22. $timeZone = new DateTimeZone($dateTimeZone);
  23. $dateTimeObject = new DateTime($dateTime, $timeZone);
  24. if ($dateTimeObject == false) {
  25. $errorMessage = $this->getLastDateTimeErrors();
  26. $className = Identifier::getName($this->getType());
  27. throw new Exception(sprintf("Could not create %s from date time string '%s': %s", $className, $dateTime, $errorMessage));
  28. }
  29. $dateTime = $dateTimeObject;
  30. } elseif (!$dateTime instanceof DateTime) {
  31. throw new Exception('Invalid first argument for some instance of AbstractTime constructor');
  32. }
  33. $this->value = $dateTime;
  34. }
  35. public function getContent()
  36. {
  37. return $this->value;
  38. }
  39. protected function getLastDateTimeErrors()
  40. {
  41. $messages = '';
  42. $lastErrors = DateTime::getLastErrors();
  43. foreach ($lastErrors['errors'] as $errorMessage) {
  44. $messages .= "{$errorMessage}, ";
  45. }
  46. return substr($messages, 0, -2);
  47. }
  48. public function __toString()
  49. {
  50. return $this->value->format("Y-m-d\tH:i:s");
  51. }
  52. protected static function extractTimeZoneData(&$binaryData, &$offsetIndex, DateTime $dateTime)
  53. {
  54. $sign = $binaryData[$offsetIndex++];
  55. $timeOffsetHours = intval(substr($binaryData, $offsetIndex, 2));
  56. $timeOffsetMinutes = intval(substr($binaryData, $offsetIndex + 2, 2));
  57. $offsetIndex += 4;
  58. $interval = new DateInterval("PT{$timeOffsetHours}H{$timeOffsetMinutes}M");
  59. if ($sign == '+') {
  60. $dateTime->sub($interval);
  61. } else {
  62. $dateTime->add($interval);
  63. }
  64. return $dateTime;
  65. }
  66. }