DateTimeHelper.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. <?php
  2. namespace fphammerle\helpers;
  3. class DateTimeHelper
  4. {
  5. const ISO8601_DATE_FORMAT = 'Y-m-d';
  6. const _timezone_iso_pattern = '(?P<tz>Z|[\+-]\d{2}.\d{2})';
  7. /**
  8. * @param integer|null $timestamp unix timestamp
  9. * @return \DateTime|null
  10. */
  11. public static function timestampToDateTime($timestamp)
  12. {
  13. if($timestamp === null) {
  14. return null;
  15. } elseif(is_int($timestamp)) {
  16. $dt = new \DateTime();
  17. $dt->setTimestamp($timestamp);
  18. return $dt;
  19. } else {
  20. throw new \InvalidArgumentException('expected integer or null');
  21. }
  22. }
  23. /**
  24. * @param string|null $text
  25. * @return \DatePeriod|null
  26. */
  27. public static function parse($text)
  28. {
  29. if($text === null) {
  30. return null;
  31. } else {
  32. if(preg_match(
  33. '/^(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})'
  34. .'([ T](?P<h>\d{2}):(?P<i>\d{2})(:(?P<s>\d{2}))?)?'
  35. . '(' . self::_timezone_iso_pattern . ')?$/',
  36. $text,
  37. $attr
  38. )) {
  39. $start = new \DateTime($text);
  40. if(!empty($attr['s'])) {
  41. $interval = new \DateInterval('PT1S');
  42. } elseif(!empty($attr['i'])) {
  43. $interval = new \DateInterval('PT1M');
  44. } else {
  45. $interval = new \DateInterval('P1D');
  46. }
  47. return new \DatePeriod($start, $interval, 0);
  48. } elseif(preg_match('/^\d{4}-(?P<m>\d{2})(( (?=-)| ?(?!-))' . self::_timezone_iso_pattern . ')?$/', $text, $attr)) {
  49. return new \DatePeriod(
  50. new \DateTime($text),
  51. new \DateInterval('P1M'),
  52. 0
  53. );
  54. } elseif(preg_match('/^(?P<y>\d{4})( ?' . self::_timezone_iso_pattern . ')?$/', $text, $attr)) {
  55. return new \DatePeriod(
  56. new \DateTime(sprintf(
  57. '%s-01-01 %s',
  58. $attr['y'],
  59. isset($attr['tz']) ? $attr['tz'] : ''
  60. )),
  61. new \DateInterval('P1Y'),
  62. 0
  63. );
  64. } else {
  65. throw new \InvalidArgumentException(
  66. sprintf("could not parse string '%s'", $text)
  67. );
  68. }
  69. }
  70. }
  71. /**
  72. * @param string|null $text
  73. * @return \DateTime|null
  74. */
  75. public static function parseGetStart($text)
  76. {
  77. $period = self::parse($text);
  78. if($period) {
  79. return $period->start;
  80. } else {
  81. return null;
  82. }
  83. }
  84. public static function deinvertInterval(\DateInterval $source = null)
  85. {
  86. // \DateInterval does not implement clone.
  87. // @see https://bugs.php.net/bug.php?id=50559
  88. $result = unserialize(serialize($source));
  89. if($result->invert) {
  90. $result->y *= -1;
  91. $result->m *= -1;
  92. $result->d *= -1;
  93. $result->h *= -1;
  94. $result->i *= -1;
  95. $result->s *= -1;
  96. $result->invert = 0;
  97. }
  98. return $result;
  99. }
  100. /**
  101. * @param \DateInterval|\DatePeriod|null $i
  102. * @return string|null
  103. */
  104. public static function iso($i)
  105. {
  106. if(is_null($i)) {
  107. return null;
  108. } elseif(sizeof(get_object_vars($i)) == 0) {
  109. throw new \InvalidArgumentException(
  110. sprintf("given instance is invalid\n%s", print_r($i, true))
  111. );
  112. } elseif($i instanceof \DateTime) {
  113. return $i->format(\DateTime::ATOM);
  114. } elseif($i instanceof \DateInterval) {
  115. $i = self::deinvertInterval($i);
  116. if($i->y < 0 || $i->m < 0 || $i->d < 0 || $i->h < 0 || $i->i < 0 || $i->s < 0) {
  117. throw new \InvalidArgumentException(
  118. sprintf("negative intervals are not supported\n%s", print_r($i, true))
  119. );
  120. } else {
  121. return StringHelper::prepend('P', StringHelper::unite([
  122. StringHelper::append($i->y ?: null, 'Y'),
  123. StringHelper::append($i->m ?: null, 'M'),
  124. StringHelper::append($i->d ?: null, 'D'),
  125. StringHelper::prepend('T', StringHelper::unite([
  126. StringHelper::append($i->h ?: null, 'H'),
  127. StringHelper::append($i->i ?: null, 'M'),
  128. StringHelper::append($i->s ?: null, 'S'),
  129. ])),
  130. ])) ?: 'P0S';
  131. }
  132. } elseif($i instanceof \DatePeriod) {
  133. // Cave:
  134. // (new \DatePeriod(
  135. // new \DateTime('2016-08-05T14:50:14Z'),
  136. // new \DateInterval('P1D'),
  137. // -1
  138. // )->recurrences == 1
  139. if($i->recurrences <= 0) {
  140. throw new \Exception(
  141. 'conversion of periods with number of occurances'
  142. . ' being negative is not supported'
  143. );
  144. }
  145. $repetitions = -1;
  146. foreach($i as $dt) {
  147. $repetitions++;
  148. // printf("%d. %s\n", $repetitions, $dt->format(\DateTime::ATOM));
  149. }
  150. // \DatePeriod::getStartDate() is available from php 5.6.5.
  151. $start_iso = self::iso($i->start);
  152. // \DatePeriod::getDateInterval() is available from php 5.6.5.
  153. // \DatePeriod::$interval returned an invalid \DatePeriod instance
  154. // in php 7.0.8
  155. $interval_iso = self::iso(get_object_vars($i)['interval']);
  156. switch($repetitions) {
  157. case -1:
  158. // no valid date within period
  159. // e.g. new \DatePeriod(
  160. // new \DateTime('2016-08-05T14:50:14+08:00'),
  161. // new \DateInterval('PT1S'),
  162. // new \DateTime('2016-08-05T14:50:14+08:00')
  163. // )
  164. throw new \InvalidArgumentException(
  165. 'given period does not contain any valid date'
  166. );
  167. case 0:
  168. return sprintf('%s/%s', $start_iso, $interval_iso);
  169. default:
  170. return sprintf('R%d/%s/%s', $repetitions, $start_iso, $interval_iso);
  171. }
  172. } else {
  173. throw new \InvalidArgumentException(sprintf(
  174. "expected \\DateTime, \\DateInterval or \\DatePeriod\n%s",
  175. print_r($i, true)
  176. ));
  177. }
  178. }
  179. }