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\UnexpectedValueException;
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';
33 * @param string $format
35 public function __construct($format = \DateTime::RFC3339)
37 $this->format = $format;
43 * @throws InvalidArgumentException
45 public function normalize($object, $format = null, array $context = array())
47 if (!$object instanceof \DateTimeInterface) {
48 throw new InvalidArgumentException('The object must implement the "\DateTimeInterface".');
51 $format = isset($context[self::FORMAT_KEY]) ? $context[self::FORMAT_KEY] : $this->format;
53 return $object->format($format);
59 public function supportsNormalization($data, $format = null)
61 return $data instanceof \DateTimeInterface;
67 * @throws UnexpectedValueException
69 public function denormalize($data, $class, $format = null, array $context = array())
71 $dateTimeFormat = isset($context[self::FORMAT_KEY]) ? $context[self::FORMAT_KEY] : null;
73 if (null !== $dateTimeFormat) {
74 $object = \DateTime::class === $class ? \DateTime::createFromFormat($dateTimeFormat, $data) : \DateTimeImmutable::createFromFormat($dateTimeFormat, $data);
76 if (false !== $object) {
80 $dateTimeErrors = \DateTime::class === $class ? \DateTime::getLastErrors() : \DateTimeImmutable::getLastErrors();
82 throw new UnexpectedValueException(sprintf(
83 'Parsing datetime string "%s" using format "%s" resulted in %d errors:'."\n".'%s',
86 $dateTimeErrors['error_count'],
87 implode("\n", $this->formatDateTimeErrors($dateTimeErrors['errors']))
92 return \DateTime::class === $class ? new \DateTime($data) : new \DateTimeImmutable($data);
93 } catch (\Exception $e) {
94 throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
101 public function supportsDenormalization($data, $type, $format = null)
103 $supportedTypes = array(
104 \DateTimeInterface::class => true,
105 \DateTimeImmutable::class => true,
106 \DateTime::class => true,
109 return isset($supportedTypes[$type]);
113 * Formats datetime errors.
115 * @param array $errors
119 private function formatDateTimeErrors(array $errors)
121 $formattedErrors = array();
123 foreach ($errors as $pos => $message) {
124 $formattedErrors[] = sprintf('at position %d: %s', $pos, $message);
127 return $formattedErrors;