aedd84a31f7a246c628532cb554d1635178981a3
[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\NotNormalizableValueException;
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     const TIMEZONE_KEY = 'datetime_timezone';
27
28     private $format;
29     private $timezone;
30
31     private static $supportedTypes = array(
32         \DateTimeInterface::class => true,
33         \DateTimeImmutable::class => true,
34         \DateTime::class => true,
35     );
36
37     /**
38      * @param string             $format
39      * @param \DateTimeZone|null $timezone
40      */
41     public function __construct($format = \DateTime::RFC3339, \DateTimeZone $timezone = null)
42     {
43         $this->format = $format;
44         $this->timezone = $timezone;
45     }
46
47     /**
48      * {@inheritdoc}
49      *
50      * @throws InvalidArgumentException
51      */
52     public function normalize($object, $format = null, array $context = array())
53     {
54         if (!$object instanceof \DateTimeInterface) {
55             throw new InvalidArgumentException('The object must implement the "\DateTimeInterface".');
56         }
57
58         $format = isset($context[self::FORMAT_KEY]) ? $context[self::FORMAT_KEY] : $this->format;
59         $timezone = $this->getTimezone($context);
60
61         if (null !== $timezone) {
62             $object = (new \DateTimeImmutable('@'.$object->getTimestamp()))->setTimezone($timezone);
63         }
64
65         return $object->format($format);
66     }
67
68     /**
69      * {@inheritdoc}
70      */
71     public function supportsNormalization($data, $format = null)
72     {
73         return $data instanceof \DateTimeInterface;
74     }
75
76     /**
77      * {@inheritdoc}
78      *
79      * @throws NotNormalizableValueException
80      */
81     public function denormalize($data, $class, $format = null, array $context = array())
82     {
83         $dateTimeFormat = isset($context[self::FORMAT_KEY]) ? $context[self::FORMAT_KEY] : null;
84         $timezone = $this->getTimezone($context);
85
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.');
88         }
89
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);
94             } else {
95                 $object = \DateTime::class === $class ? \DateTime::createFromFormat($dateTimeFormat, $data, $timezone) : \DateTimeImmutable::createFromFormat($dateTimeFormat, $data, $timezone);
96             }
97
98             if (false !== $object) {
99                 return $object;
100             }
101
102             $dateTimeErrors = \DateTime::class === $class ? \DateTime::getLastErrors() : \DateTimeImmutable::getLastErrors();
103
104             throw new NotNormalizableValueException(sprintf(
105                 'Parsing datetime string "%s" using format "%s" resulted in %d errors:'."\n".'%s',
106                 $data,
107                 $dateTimeFormat,
108                 $dateTimeErrors['error_count'],
109                 implode("\n", $this->formatDateTimeErrors($dateTimeErrors['errors']))
110             ));
111         }
112
113         try {
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);
117         }
118     }
119
120     /**
121      * {@inheritdoc}
122      */
123     public function supportsDenormalization($data, $type, $format = null)
124     {
125         return isset(self::$supportedTypes[$type]);
126     }
127
128     /**
129      * Formats datetime errors.
130      *
131      * @return string[]
132      */
133     private function formatDateTimeErrors(array $errors)
134     {
135         $formattedErrors = array();
136
137         foreach ($errors as $pos => $message) {
138             $formattedErrors[] = sprintf('at position %d: %s', $pos, $message);
139         }
140
141         return $formattedErrors;
142     }
143
144     private function getTimezone(array $context)
145     {
146         $dateTimeZone = array_key_exists(self::TIMEZONE_KEY, $context) ? $context[self::TIMEZONE_KEY] : $this->timezone;
147
148         if (null === $dateTimeZone) {
149             return null;
150         }
151
152         return $dateTimeZone instanceof \DateTimeZone ? $dateTimeZone : new \DateTimeZone($dateTimeZone);
153     }
154 }