DateTimeToTimestampTransformer.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace Symfony\Component\Form\ValueTransformer;
  3. /*
  4. * This file is part of the Symfony framework.
  5. *
  6. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  7. *
  8. * This source file is subject to the MIT license that is bundled
  9. * with this source code in the file LICENSE.
  10. */
  11. use Symfony\Component\Form\Exception\UnexpectedTypeException;
  12. /**
  13. * Transforms between a timestamp and a DateTime object
  14. *
  15. * @author Bernhard Schussek <bernhard.schussek@symfony-project.com>
  16. * @author Florian Eckerstorfer <florian@eckerstorfer.org>
  17. */
  18. class DateTimeToTimestampTransformer extends BaseValueTransformer
  19. {
  20. /**
  21. * {@inheritDoc}
  22. */
  23. protected function configure()
  24. {
  25. $this->addOption('input_timezone', 'UTC');
  26. $this->addOption('output_timezone', 'UTC');
  27. parent::configure();
  28. }
  29. /**
  30. * Transforms a DateTime object into a timestamp in the configured timezone
  31. *
  32. * @param DateTime $value A DateTime object
  33. * @return integer A timestamp
  34. */
  35. public function transform($value)
  36. {
  37. if (null === $value) {
  38. return null;
  39. }
  40. if (!$value instanceof \DateTime) {
  41. throw new UnexpectedTypeException($value, '\DateTime');
  42. }
  43. $value->setTimezone(new \DateTimeZone($this->getOption('output_timezone')));
  44. return (int)$value->format('U');
  45. }
  46. /**
  47. * Transforms a timestamp in the configured timezone into a DateTime object
  48. *
  49. * @param string $value A value as produced by PHP's date() function
  50. * @return DateTime A DateTime object
  51. */
  52. public function reverseTransform($value, $originalValue)
  53. {
  54. if (null === $value) {
  55. return null;
  56. }
  57. if (!is_numeric($value)) {
  58. throw new UnexpectedTypeException($value, 'numeric');
  59. }
  60. $outputTimezone = $this->getOption('output_timezone');
  61. $inputTimezone = $this->getOption('input_timezone');
  62. try {
  63. $dateTime = new \DateTime("@$value $outputTimezone");
  64. if ($inputTimezone != $outputTimezone) {
  65. $dateTime->setTimezone(new \DateTimeZone($inputTimezone));
  66. }
  67. return $dateTime;
  68. } catch (\Exception $e) {
  69. throw new \InvalidArgumentException('Expected a valid timestamp. ' . $e->getMessage(), 0, $e);
  70. }
  71. }
  72. }