Debian Codegraph @

lib/3rdParty/composer/symfony/serializer/Normalizer/DateTimeNormalizer.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
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 <[email protected]>
22 */
23 final class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface
24 {
25 public const FORMAT_KEY = 'datetime_format';
26 public const TIMEZONE_KEY = 'datetime_timezone';
27 public const CAST_KEY = 'datetime_cast';
28 public const FORCE_TIMEZONE_KEY = 'datetime_force_timezone';
29
30 private array $defaultContext = [
31 self::FORMAT_KEY => \DateTimeInterface::RFC3339,
32 self::TIMEZONE_KEY => null,
33 self::CAST_KEY => null,
34 self::FORCE_TIMEZONE_KEY => false,
35 ];
36
37 private const SUPPORTED_TYPES = [
38 \DateTimeInterface::class => true,
39 \DateTimeImmutable::class => true,
40 \DateTime::class => true,
41 ];
42
43 public function __construct(array $defaultContext = [])
44 {
45 $this->setDefaultContext($defaultContext);
46 }
47
48 public function setDefaultContext(array $defaultContext): void
49 {
50 $this->defaultContext = array_merge($this->defaultContext, $defaultContext);
51 }
52
53 public function getSupportedTypes(?string $format): array
54 {
55 return self::SUPPORTED_TYPES;
56 }
57
58 /**
59 * @throws InvalidArgumentException
60 */
61 public function normalize(mixed $data, ?string $format = null, array $context = []): int|float|string
62 {
63 if (!$data instanceof \DateTimeInterface) {
64 throw new InvalidArgumentException('The object must implement the "\DateTimeInterface".');
65 }
66
67 $dateTimeFormat = $context[self::FORMAT_KEY] ?? $this->defaultContext[self::FORMAT_KEY];
68 $timezone = $this->getTimezone($context);
69
70 if (null !== $timezone) {
71 $data = clone $data;
72 $data = $data->setTimezone($timezone);
73 }
74
75 return match ($context[self::CAST_KEY] ?? $this->defaultContext[self::CAST_KEY] ?? false) {
76 'int' => (int) $data->format($dateTimeFormat),
77 'float' => (float) $data->format($dateTimeFormat),
78 default => $data->format($dateTimeFormat),
79 };
80 }
81
82 public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
83 {
84 return $data instanceof \DateTimeInterface;
85 }
86
87 /**
88 * @throws NotNormalizableValueException
89 */
90 public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): \DateTimeInterface
91 {
92 if (\is_int($data) || \is_float($data)) {
93 switch ($context[self::FORMAT_KEY] ?? $this->defaultContext[self::FORMAT_KEY] ?? null) {
94 case 'U':
95 $data = \sprintf('%d', $data);
96 break;
97 case 'U.u':
98 $data = \sprintf('%.6F', $data);
99 break;
100 }
101 }
102
103 if (!\is_string($data) || '' === trim($data)) {
104 throw NotNormalizableValueException::createForUnexpectedDataType('The data is either not an string, an empty string, or null; you should pass a string that can be parsed with the passed format or a valid DateTime string.', $data, ['string'], $context['deserialization_path'] ?? null, true);
105 }
106
107 try {
108 if (\DateTimeInterface::class === $type) {
109 $type = \DateTimeImmutable::class;
110 }
111
112 $timezone = $this->getTimezone($context);
113 $dateTimeFormat = $context[self::FORMAT_KEY] ?? null;
114
115 if (null !== $dateTimeFormat) {
116 if (false !== $object = $type::createFromFormat($dateTimeFormat, $data, $timezone)) {
117 return $this->enforceTimezone($object, $context);
118 }
119
120 $dateTimeErrors = $type::getLastErrors();
121
122 throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('Parsing datetime string "%s" using format "%s" resulted in %d errors: ', $data, $dateTimeFormat, $dateTimeErrors['error_count'])."\n".implode("\n", $this->formatDateTimeErrors($dateTimeErrors['errors'])), $data, ['string'], $context['deserialization_path'] ?? null, true);
123 }
124
125 $defaultDateTimeFormat = $this->defaultContext[self::FORMAT_KEY] ?? null;
126
127 if (null !== $defaultDateTimeFormat) {
128 if (false !== $object = $type::createFromFormat($defaultDateTimeFormat, $data, $timezone)) {
129 return $this->enforceTimezone($object, $context);
130 }
131 }
132
133 return $this->enforceTimezone(new $type($data, $timezone), $context);
134 } catch (NotNormalizableValueException $e) {
135 throw $e;
136 } catch (\Exception $e) {
137 throw NotNormalizableValueException::createForUnexpectedDataType($e->getMessage(), $data, ['string'], $context['deserialization_path'] ?? null, false, $e->getCode(), $e);
138 }
139 }
140
141 public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
142 {
143 return is_a($type, \DateTimeInterface::class, true);
144 }
145
146 /**
147 * Formats datetime errors.
148 *
149 * @return string[]
150 */
151 private function formatDateTimeErrors(array $errors): array
152 {
153 $formattedErrors = [];
154
155 foreach ($errors as $pos => $message) {
156 $formattedErrors[] = \sprintf('at position %d: %s', $pos, $message);
157 }
158
159 return $formattedErrors;
160 }
161
162 private function getTimezone(array $context): ?\DateTimeZone
163 {
164 $dateTimeZone = $context[self::TIMEZONE_KEY] ?? $this->defaultContext[self::TIMEZONE_KEY];
165
166 if (null === $dateTimeZone) {
167 return null;
168 }
169
170 return $dateTimeZone instanceof \DateTimeZone ? $dateTimeZone : new \DateTimeZone($dateTimeZone);
171 }
172
173 private function enforceTimezone(\DateTime|\DateTimeImmutable $object, array $context): \DateTimeInterface
174 {
175 $timezone = $this->getTimezone($context);
176 $forceTimezone = $context[self::FORCE_TIMEZONE_KEY] ?? $this->defaultContext[self::FORCE_TIMEZONE_KEY];
177
178 if (null === $timezone || !$forceTimezone) {
179 return $object;
180 }
181
182 return $object->setTimezone($timezone);
183 }
184 }