Spaces:
Runtime error
Runtime error
File size: 6,620 Bytes
7a66774 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Serializer\Normalizer;
use Symfony\Component\PropertyInfo\Type;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
/**
* Normalizes an object implementing the {@see \DateTimeInterface} to a date string.
* Denormalizes a date string to an instance of {@see \DateTime} or {@see \DateTimeImmutable}.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*
* @final since Symfony 6.3
*/
class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface, CacheableSupportsMethodInterface
{
public const FORMAT_KEY = 'datetime_format';
public const TIMEZONE_KEY = 'datetime_timezone';
private array $defaultContext = [
self::FORMAT_KEY => \DateTimeInterface::RFC3339,
self::TIMEZONE_KEY => null,
];
private const SUPPORTED_TYPES = [
\DateTimeInterface::class => true,
\DateTimeImmutable::class => true,
\DateTime::class => true,
];
public function __construct(array $defaultContext = [])
{
$this->setDefaultContext($defaultContext);
}
public function setDefaultContext(array $defaultContext): void
{
$this->defaultContext = array_merge($this->defaultContext, $defaultContext);
}
public function getSupportedTypes(?string $format): array
{
$isCacheable = __CLASS__ === static::class || $this->hasCacheableSupportsMethod();
return [
\DateTimeInterface::class => $isCacheable,
\DateTimeImmutable::class => $isCacheable,
\DateTime::class => $isCacheable,
];
}
/**
* @throws InvalidArgumentException
*/
public function normalize(mixed $object, ?string $format = null, array $context = []): string
{
if (!$object instanceof \DateTimeInterface) {
throw new InvalidArgumentException('The object must implement the "\DateTimeInterface".');
}
$dateTimeFormat = $context[self::FORMAT_KEY] ?? $this->defaultContext[self::FORMAT_KEY];
$timezone = $this->getTimezone($context);
if (null !== $timezone) {
$object = clone $object;
$object = $object->setTimezone($timezone);
}
return $object->format($dateTimeFormat);
}
/**
* @param array $context
*/
public function supportsNormalization(mixed $data, ?string $format = null /* , array $context = [] */): bool
{
return $data instanceof \DateTimeInterface;
}
/**
* @throws NotNormalizableValueException
*/
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): \DateTimeInterface
{
if (\is_int($data) || \is_float($data)) {
switch ($context[self::FORMAT_KEY] ?? $this->defaultContext[self::FORMAT_KEY] ?? null) {
case 'U': $data = \sprintf('%d', $data); break;
case 'U.u': $data = \sprintf('%.6F', $data); break;
}
}
if (!\is_string($data) || '' === trim($data)) {
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, [Type::BUILTIN_TYPE_STRING], $context['deserialization_path'] ?? null, true);
}
try {
if (\DateTimeInterface::class === $type) {
$type = \DateTimeImmutable::class;
}
$timezone = $this->getTimezone($context);
$dateTimeFormat = $context[self::FORMAT_KEY] ?? null;
if (null !== $dateTimeFormat) {
if (false !== $object = $type::createFromFormat($dateTimeFormat, $data, $timezone)) {
return $object;
}
$dateTimeErrors = $type::getLastErrors();
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, [Type::BUILTIN_TYPE_STRING], $context['deserialization_path'] ?? null, true);
}
$defaultDateTimeFormat = $this->defaultContext[self::FORMAT_KEY] ?? null;
if (null !== $defaultDateTimeFormat) {
if (false !== $object = $type::createFromFormat($defaultDateTimeFormat, $data, $timezone)) {
return $object;
}
}
return new $type($data, $timezone);
} catch (NotNormalizableValueException $e) {
throw $e;
} catch (\Exception $e) {
throw NotNormalizableValueException::createForUnexpectedDataType($e->getMessage(), $data, [Type::BUILTIN_TYPE_STRING], $context['deserialization_path'] ?? null, false, $e->getCode(), $e);
}
}
/**
* @param array $context
*/
public function supportsDenormalization(mixed $data, string $type, ?string $format = null /* , array $context = [] */): bool
{
return isset(self::SUPPORTED_TYPES[$type]);
}
/**
* @deprecated since Symfony 6.3, use "getSupportedTypes()" instead
*/
public function hasCacheableSupportsMethod(): bool
{
trigger_deprecation('symfony/serializer', '6.3', 'The "%s()" method is deprecated, implement "%s::getSupportedTypes()" instead.', __METHOD__, get_debug_type($this));
return __CLASS__ === static::class;
}
/**
* Formats datetime errors.
*
* @return string[]
*/
private function formatDateTimeErrors(array $errors): array
{
$formattedErrors = [];
foreach ($errors as $pos => $message) {
$formattedErrors[] = \sprintf('at position %d: %s', $pos, $message);
}
return $formattedErrors;
}
private function getTimezone(array $context): ?\DateTimeZone
{
$dateTimeZone = $context[self::TIMEZONE_KEY] ?? $this->defaultContext[self::TIMEZONE_KEY];
if (null === $dateTimeZone) {
return null;
}
return $dateTimeZone instanceof \DateTimeZone ? $dateTimeZone : new \DateTimeZone($dateTimeZone);
}
}
|