CookieUtil.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace Http\Message;
  3. use Http\Message\Exception\UnexpectedValueException;
  4. final class CookieUtil
  5. {
  6. /**
  7. * Handles dates as defined by RFC 2616 section 3.3.1, and also some other
  8. * non-standard, but common formats.
  9. *
  10. * @var array
  11. */
  12. private static $dateFormats = [
  13. 'D, d M y H:i:s T',
  14. 'D, d M Y H:i:s T',
  15. 'D, d-M-y H:i:s T',
  16. 'D, d-M-Y H:i:s T',
  17. 'D, d-m-y H:i:s T',
  18. 'D, d-m-Y H:i:s T',
  19. 'D M j G:i:s Y',
  20. 'D M d H:i:s Y T',
  21. ];
  22. /**
  23. * @see https://github.com/symfony/symfony/blob/master/src/Symfony/Component/BrowserKit/Cookie.php
  24. *
  25. * @param string $dateValue
  26. *
  27. * @return \DateTime
  28. *
  29. * @throws UnexpectedValueException if we cannot parse the cookie date string
  30. */
  31. public static function parseDate($dateValue)
  32. {
  33. foreach (self::$dateFormats as $dateFormat) {
  34. if (false !== $date = \DateTime::createFromFormat($dateFormat, $dateValue, new \DateTimeZone('GMT'))) {
  35. return $date;
  36. }
  37. }
  38. // attempt a fallback for unusual formatting
  39. if (false !== $date = date_create($dateValue, new \DateTimeZone('GMT'))) {
  40. return $date;
  41. }
  42. throw new UnexpectedValueException(sprintf(
  43. 'Unparseable cookie date string "%s"',
  44. $dateValue
  45. ));
  46. }
  47. }