DateTimeNormalizer.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.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 Symfony\Component\Serializer\Normalizer;
  11. use Symfony\Component\Serializer\Exception\InvalidArgumentException;
  12. use Symfony\Component\Serializer\Exception\UnexpectedValueException;
  13. /**
  14. * Normalizes an object implementing the {@see \DateTimeInterface} to a date string.
  15. * Denormalizes a date string to an instance of {@see \DateTime} or {@see \DateTimeImmutable}.
  16. *
  17. * @author Kévin Dunglas <dunglas@gmail.com>
  18. */
  19. class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface
  20. {
  21. const FORMAT_KEY = 'datetime_format';
  22. /**
  23. * @var string
  24. */
  25. private $format;
  26. /**
  27. * @param string $format
  28. */
  29. public function __construct($format = \DateTime::RFC3339)
  30. {
  31. $this->format = $format;
  32. }
  33. /**
  34. * {@inheritdoc}
  35. *
  36. * @throws InvalidArgumentException
  37. */
  38. public function normalize($object, $format = null, array $context = array())
  39. {
  40. if (!$object instanceof \DateTimeInterface) {
  41. throw new InvalidArgumentException('The object must implement the "\DateTimeInterface".');
  42. }
  43. $format = isset($context[self::FORMAT_KEY]) ? $context[self::FORMAT_KEY] : $this->format;
  44. return $object->format($format);
  45. }
  46. /**
  47. * {@inheritdoc}
  48. */
  49. public function supportsNormalization($data, $format = null)
  50. {
  51. return $data instanceof \DateTimeInterface;
  52. }
  53. /**
  54. * {@inheritdoc}
  55. *
  56. * @throws UnexpectedValueException
  57. */
  58. public function denormalize($data, $class, $format = null, array $context = array())
  59. {
  60. try {
  61. return \DateTime::class === $class ? new \DateTime($data) : new \DateTimeImmutable($data);
  62. } catch (\Exception $e) {
  63. throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
  64. }
  65. }
  66. /**
  67. * {@inheritdoc}
  68. */
  69. public function supportsDenormalization($data, $type, $format = null)
  70. {
  71. $supportedTypes = array(
  72. \DateTimeInterface::class => true,
  73. \DateTimeImmutable::class => true,
  74. \DateTime::class => true,
  75. );
  76. return isset($supportedTypes[$type]);
  77. }
  78. }