4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Serializer\Normalizer;
14 use Symfony\Component\Serializer\Exception\InvalidArgumentException;
15 use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
18 * Normalizes an object implementing the {@see \DateTimeInterface} to a date string.
19 * Denormalizes a date string to an instance of {@see \DateTime} or {@see \DateTimeImmutable}.
21 * @author Kévin Dunglas <dunglas@gmail.com>
23 class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface
25 const FORMAT_KEY = 'datetime_format';
26 const TIMEZONE_KEY = 'datetime_timezone';
31 private static $supportedTypes = array(
32 \DateTimeInterface::class => true,
33 \DateTimeImmutable::class => true,
34 \DateTime::class => true,
38 * @param string $format
39 * @param \DateTimeZone|null $timezone
41 public function __construct($format = \DateTime::RFC3339, \DateTimeZone $timezone = null)
43 $this->format = $format;
44 $this->timezone = $timezone;
50 * @throws InvalidArgumentException
52 public function normalize($object, $format = null, array $context = array())
54 if (!$object instanceof \DateTimeInterface) {
55 throw new InvalidArgumentException('The object must implement the "\DateTimeInterface".');
58 $format = isset($context[self::FORMAT_KEY]) ? $context[self::FORMAT_KEY] : $this->format;
59 $timezone = $this->getTimezone($context);
61 if (null !== $timezone) {
62 $object = (new \DateTimeImmutable('@'.$object->getTimestamp()))->setTimezone($timezone);
65 return $object->format($format);
71 public function supportsNormalization($data, $format = null)
73 return $data instanceof \DateTimeInterface;
79 * @throws NotNormalizableValueException
81 public function denormalize($data, $class, $format = null, array $context = array())
83 $dateTimeFormat = isset($context[self::FORMAT_KEY]) ? $context[self::FORMAT_KEY] : null;
84 $timezone = $this->getTimezone($context);
86 if ('' === $data || null === $data) {
87 throw new NotNormalizableValueException('The data is either an empty string or null, you should pass a string that can be parsed with the passed format or a valid DateTime string.');
90 if (null !== $dateTimeFormat) {
91 if (null === $timezone && \PHP_VERSION_ID < 70000) {
92 // https://bugs.php.net/bug.php?id=68669
93 $object = \DateTime::class === $class ? \DateTime::createFromFormat($dateTimeFormat, $data) : \DateTimeImmutable::createFromFormat($dateTimeFormat, $data);
95 $object = \DateTime::class === $class ? \DateTime::createFromFormat($dateTimeFormat, $data, $timezone) : \DateTimeImmutable::createFromFormat($dateTimeFormat, $data, $timezone);
98 if (false !== $object) {
102 $dateTimeErrors = \DateTime::class === $class ? \DateTime::getLastErrors() : \DateTimeImmutable::getLastErrors();
104 throw new NotNormalizableValueException(sprintf(
105 'Parsing datetime string "%s" using format "%s" resulted in %d errors:'."\n".'%s',
108 $dateTimeErrors['error_count'],
109 implode("\n", $this->formatDateTimeErrors($dateTimeErrors['errors']))
114 return \DateTime::class === $class ? new \DateTime($data, $timezone) : new \DateTimeImmutable($data, $timezone);
115 } catch (\Exception $e) {
116 throw new NotNormalizableValueException($e->getMessage(), $e->getCode(), $e);
123 public function supportsDenormalization($data, $type, $format = null)
125 return isset(self::$supportedTypes[$type]);
129 * Formats datetime errors.
133 private function formatDateTimeErrors(array $errors)
135 $formattedErrors = array();
137 foreach ($errors as $pos => $message) {
138 $formattedErrors[] = sprintf('at position %d: %s', $pos, $message);
141 return $formattedErrors;
144 private function getTimezone(array $context)
146 $dateTimeZone = array_key_exists(self::TIMEZONE_KEY, $context) ? $context[self::TIMEZONE_KEY] : $this->timezone;
148 if (null === $dateTimeZone) {
152 return $dateTimeZone instanceof \DateTimeZone ? $dateTimeZone : new \DateTimeZone($dateTimeZone);