Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Symfony/Component/Serializer/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ CHANGELOG
* Deprecate class aliases in the `Annotation` namespace, use attributes instead
* Deprecate getters in attribute classes in favor of public properties
* Deprecate `ClassMetadataFactoryCompiler`
* Add `FORCE_TIMEZONE_KEY` to `DateTimeNormalizer` to force the timezone during denormalization

7.3
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,14 @@ public function withFormat(?string $format): static
*
* @see https://secure.php.net/manual/en/class.datetimezone.php
*
* @param ?bool $force Whether to enforce the timezone during denormalization
*
* @throws InvalidArgumentException
*/
public function withTimezone(\DateTimeZone|string|null $timezone): static
public function withTimezone(\DateTimeZone|string|null $timezone, ?bool $force = null): static
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
public function withTimezone(\DateTimeZone|string|null $timezone, ?bool $force = null): static
public function withTimezone(\DateTimeZone|string|null $timezone, bool $force = false): static

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought about setting it to true|false but in the implementation there's a "default context" and given context. Basicly you could set default context to ->withTimezone(null, true), and in your custom context ->withTimezone('UTC, null). In this way for every context the timezone will be forced, but per serializer context you can enforce different timezones.

{
if (null === $timezone) {
return $this->with(DateTimeNormalizer::TIMEZONE_KEY, null);
return $this->with(DateTimeNormalizer::TIMEZONE_KEY, null)->with(DateTimeNormalizer::FORCE_TIMEZONE_KEY, $force);
}

if (\is_string($timezone)) {
Expand All @@ -59,7 +61,7 @@ public function withTimezone(\DateTimeZone|string|null $timezone): static
}
}

return $this->with(DateTimeNormalizer::TIMEZONE_KEY, $timezone);
return $this->with(DateTimeNormalizer::TIMEZONE_KEY, $timezone)->with(DateTimeNormalizer::FORCE_TIMEZONE_KEY, $force);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,10 @@
],
"description": "Timezone of the date (DateTimeNormalizer)"
},
"forceTimezone": {
"type": "boolean",
"description": "Whether to enforce the timezone during denormalization (DateTimeNormalizer)"
},
"cast": {
"enum": ["int", "float"],
"description": "Cast type for DateTime (DateTimeNormalizer)"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,13 @@ final class DateTimeNormalizer implements NormalizerInterface, DenormalizerInter
public const FORMAT_KEY = 'datetime_format';
public const TIMEZONE_KEY = 'datetime_timezone';
public const CAST_KEY = 'datetime_cast';
public const FORCE_TIMEZONE_KEY = 'datetime_force_timezone';

private array $defaultContext = [
self::FORMAT_KEY => \DateTimeInterface::RFC3339,
self::TIMEZONE_KEY => null,
self::CAST_KEY => null,
self::FORCE_TIMEZONE_KEY => false,
];

private const SUPPORTED_TYPES = [
Expand Down Expand Up @@ -112,7 +114,7 @@ public function denormalize(mixed $data, string $type, ?string $format = null, a

if (null !== $dateTimeFormat) {
if (false !== $object = $type::createFromFormat($dateTimeFormat, $data, $timezone)) {
return $object;
return $this->enforceTimezone($object, $context);
}

$dateTimeErrors = $type::getLastErrors();
Expand All @@ -124,11 +126,11 @@ public function denormalize(mixed $data, string $type, ?string $format = null, a

if (null !== $defaultDateTimeFormat) {
if (false !== $object = $type::createFromFormat($defaultDateTimeFormat, $data, $timezone)) {
return $object;
return $this->enforceTimezone($object, $context);
}
}

return new $type($data, $timezone);
return $this->enforceTimezone(new $type($data, $timezone), $context);
} catch (NotNormalizableValueException $e) {
throw $e;
} catch (\Exception $e) {
Expand Down Expand Up @@ -167,4 +169,16 @@ private function getTimezone(array $context): ?\DateTimeZone

return $dateTimeZone instanceof \DateTimeZone ? $dateTimeZone : new \DateTimeZone($dateTimeZone);
}

private function enforceTimezone(\DateTime|\DateTimeImmutable $object, array $context): \DateTimeInterface
{
$timezone = $this->getTimezone($context);
$forceTimezone = $context[self::FORCE_TIMEZONE_KEY] ?? $this->defaultContext[self::FORCE_TIMEZONE_KEY];

if (null === $timezone || !$forceTimezone) {
return $object;
}

return $object->setTimezone($timezone);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function testWithers(array $values)
{
$context = $this->contextBuilder
->withFormat($values[DateTimeNormalizer::FORMAT_KEY])
->withTimezone($values[DateTimeNormalizer::TIMEZONE_KEY])
->withTimezone($values[DateTimeNormalizer::TIMEZONE_KEY], $values[DateTimeNormalizer::FORCE_TIMEZONE_KEY])
->withCast($values[DateTimeNormalizer::CAST_KEY])
->toArray();

Expand All @@ -53,18 +53,23 @@ public static function withersDataProvider(): iterable
DateTimeNormalizer::FORMAT_KEY => 'format',
DateTimeNormalizer::TIMEZONE_KEY => new \DateTimeZone('GMT'),
DateTimeNormalizer::CAST_KEY => 'int',
DateTimeNormalizer::FORCE_TIMEZONE_KEY => true,
]];

yield 'With null values' => [[
DateTimeNormalizer::FORMAT_KEY => null,
DateTimeNormalizer::TIMEZONE_KEY => null,
DateTimeNormalizer::CAST_KEY => null,
DateTimeNormalizer::FORCE_TIMEZONE_KEY => null,
]];
}

public function testCastTimezoneStringToTimezone()
{
$this->assertEquals([DateTimeNormalizer::TIMEZONE_KEY => new \DateTimeZone('GMT')], $this->contextBuilder->withTimezone('GMT')->toArray());
$this->assertEquals(
[DateTimeNormalizer::TIMEZONE_KEY => new \DateTimeZone('GMT'), DateTimeNormalizer::FORCE_TIMEZONE_KEY => null],
$this->contextBuilder->withTimezone('GMT')->toArray()
);
}

public function testCannotSetInvalidTimezone()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,59 @@ public static function denormalizeUsingTimezonePassedInContextProvider()
];
}

public function testDenormalizeUsingPreserveContextTimezoneAndFormatPassedInConstructor()
{
$normalizer = new DateTimeNormalizer(
[
DateTimeNormalizer::TIMEZONE_KEY => new \DateTimeZone('Japan'),
DateTimeNormalizer::FORMAT_KEY => 'Y-m-d\\TH:i:sO',
DateTimeNormalizer::FORCE_TIMEZONE_KEY => true,
]
);
$actual = $normalizer->denormalize('2016-12-01T12:34:56+0000', \DateTimeInterface::class);
$this->assertEquals(new \DateTimeZone('Japan'), $actual->getTimezone());
}

public function testDenormalizeUsingPreserveContextTimezoneAndFormatPassedInContext()
{
$actual = $this->normalizer->denormalize(
'2016-12-01T12:34:56+0000',
\DateTimeInterface::class,
null,
[
DateTimeNormalizer::TIMEZONE_KEY => new \DateTimeZone('Japan'),
DateTimeNormalizer::FORMAT_KEY => 'Y-m-d\\TH:i:sO',
DateTimeNormalizer::FORCE_TIMEZONE_KEY => true,
]
);
$this->assertEquals(new \DateTimeZone('Japan'), $actual->getTimezone());
}

public function testDenormalizeUsingPreserveContextTimezoneWithoutFormat()
{
$actual = $this->normalizer->denormalize(
'2016-12-01T12:34:56+0000',
\DateTimeInterface::class,
null,
[
DateTimeNormalizer::TIMEZONE_KEY => new \DateTimeZone('Japan'),
DateTimeNormalizer::FORCE_TIMEZONE_KEY => true,
]
);
$this->assertEquals(new \DateTimeZone('Japan'), $actual->getTimezone());
}

public function testDenormalizeUsingPreserveContextShouldBeIgnoredWithoutTimezoneInContext()
{
$actual = $this->normalizer->denormalize(
'2016-12-01T12:34:56+0000',
\DateTimeInterface::class,
null,
[DateTimeNormalizer::FORCE_TIMEZONE_KEY => true]
);
$this->assertEquals(new \DateTimeZone('+00:00'), $actual->getTimezone());
}

public function testDenormalizeInvalidDataThrowsException()
{
$this->expectException(UnexpectedValueException::class);
Expand Down
Loading