5958aab0679bdc63b3a171e353141c413f7bc548
[yaffs-website] / vendor / symfony / serializer / Normalizer / DateTimeNormalizer.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\Serializer\Normalizer;
13
14 use Symfony\Component\Serializer\Exception\InvalidArgumentException;
15 use Symfony\Component\Serializer\Exception\UnexpectedValueException;
16
17 /**
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}.
20  *
21  * @author Kévin Dunglas <dunglas@gmail.com>
22  */
23 class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface
24 {
25     const FORMAT_KEY = 'datetime_format';
26
27     /**
28      * @var string
29      */
30     private $format;
31
32     /**
33      * @param string $format
34      */
35     public function __construct($format = \DateTime::RFC3339)
36     {
37         $this->format = $format;
38     }
39
40     /**
41      * {@inheritdoc}
42      *
43      * @throws InvalidArgumentException
44      */
45     public function normalize($object, $format = null, array $context = array())
46     {
47         if (!$object instanceof \DateTimeInterface) {
48             throw new InvalidArgumentException('The object must implement the "\DateTimeInterface".');
49         }
50
51         $format = isset($context[self::FORMAT_KEY]) ? $context[self::FORMAT_KEY] : $this->format;
52
53         return $object->format($format);
54     }
55
56     /**
57      * {@inheritdoc}
58      */
59     public function supportsNormalization($data, $format = null)
60     {
61         return $data instanceof \DateTimeInterface;
62     }
63
64     /**
65      * {@inheritdoc}
66      *
67      * @throws UnexpectedValueException
68      */
69     public function denormalize($data, $class, $format = null, array $context = array())
70     {
71         $dateTimeFormat = isset($context[self::FORMAT_KEY]) ? $context[self::FORMAT_KEY] : null;
72
73         if (null !== $dateTimeFormat) {
74             $object = \DateTime::class === $class ? \DateTime::createFromFormat($dateTimeFormat, $data) : \DateTimeImmutable::createFromFormat($dateTimeFormat, $data);
75
76             if (false !== $object) {
77                 return $object;
78             }
79
80             $dateTimeErrors = \DateTime::class === $class ? \DateTime::getLastErrors() : \DateTimeImmutable::getLastErrors();
81
82             throw new UnexpectedValueException(sprintf(
83                 'Parsing datetime string "%s" using format "%s" resulted in %d errors:'."\n".'%s',
84                 $data,
85                 $dateTimeFormat,
86                 $dateTimeErrors['error_count'],
87                 implode("\n", $this->formatDateTimeErrors($dateTimeErrors['errors']))
88             ));
89         }
90
91         try {
92             return \DateTime::class === $class ? new \DateTime($data) : new \DateTimeImmutable($data);
93         } catch (\Exception $e) {
94             throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
95         }
96     }
97
98     /**
99      * {@inheritdoc}
100      */
101     public function supportsDenormalization($data, $type, $format = null)
102     {
103         $supportedTypes = array(
104             \DateTimeInterface::class => true,
105             \DateTimeImmutable::class => true,
106             \DateTime::class => true,
107         );
108
109         return isset($supportedTypes[$type]);
110     }
111
112     /**
113      * Formats datetime errors.
114      *
115      * @param array $errors
116      *
117      * @return string[]
118      */
119     private function formatDateTimeErrors(array $errors)
120     {
121         $formattedErrors = array();
122
123         foreach ($errors as $pos => $message) {
124             $formattedErrors[] = sprintf('at position %d: %s', $pos, $message);
125         }
126
127         return $formattedErrors;
128     }
129 }