Skip to content

[Serializer] Provide option to always apply timezone of the DateTimeNormalizer context. #31256

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
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
68 changes: 61 additions & 7 deletions src/Symfony/Component/Serializer/Normalizer/DateTimeNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,17 @@ class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface,
const FORMAT_KEY = 'datetime_format';
const TIMEZONE_KEY = 'datetime_timezone';

private $defaultContext = [
self::FORMAT_KEY => \DateTime::RFC3339,
self::TIMEZONE_KEY => null,
];

/**
* In PHP, the $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. @946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).
*
* The denormalizer assumes that all DateTimeInterface object returned will have the timezone returned by the getTimezone() method.
* Default PHP behavior will occur if the getTimezone() method returns null or context[self::PRESERVE_CONTEXT_TIMEZONE] is set to false.
* This flag will be ignored in Symfony 5.0+
Copy link
Member

Choose a reason for hiding this comment

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

6.0?

*/
const PRESERVE_CONTEXT_TIMEZONE = 'preserve_context_timezone';

private $defaultContext;

private static $supportedTypes = [
\DateTimeInterface::class => true,
Expand All @@ -38,6 +45,24 @@ class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface,

public function __construct(array $defaultContext = [])
{
$this->defaultContext = [
self::FORMAT_KEY => \DateTime::RFC3339,
self::TIMEZONE_KEY => null,
];

if (!\is_array($defaultContext)) {
Copy link
Member

Choose a reason for hiding this comment

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

$defaultContext is always an array as there is a type hint in the constructor signature.

@trigger_error('Passing the date time format directly to the constructor is deprecated since Symfony 4.2, use the default context instead.', E_USER_DEPRECATED);

$defaultContext = [self::FORMAT_KEY => (string) $defaultContext];
$defaultContext[self::TIMEZONE_KEY] = $timezone;
}

if (!isset($defaultContext[self::TIMEZONE_KEY]) && null !== $timezone) {
Copy link
Member

Choose a reason for hiding this comment

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

There is no $timezone variable in the constructor.

Copy link
Author

Choose a reason for hiding this comment

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

There was a $timezone and $defaultContext was not always an array when this was written.

@trigger_error('Passing the time zone directly to the constructor is deprecated since Symfony 4.2, use the default context instead.', E_USER_DEPRECATED);

$defaultContext[self::TIMEZONE_KEY] = $timezone;
}

$this->defaultContext = array_merge($this->defaultContext, $defaultContext);
}

Expand Down Expand Up @@ -80,16 +105,21 @@ public function denormalize($data, $class, string $format = null, array $context
{
$dateTimeFormat = $context[self::FORMAT_KEY] ?? null;
$timezone = $this->getTimezone($context);
$preserveContextTimezone = $this->isPreserveContextTimezone($context);

if ('' === $data || null === $data) {
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.');
}

if (null !== $dateTimeFormat) {
$object = \DateTime::class === $class ? \DateTime::createFromFormat($dateTimeFormat, $data, $timezone) : \DateTimeImmutable::createFromFormat($dateTimeFormat, $data, $timezone);
$object = \DateTime::createFromFormat($dateTimeFormat, $data, $timezone);

if (false !== $object) {
return $object;
if ($preserveContextTimezone) {
$object->setTimezone($timezone);
}

return \DateTime::class === $class ? $object : new \DateTimeImmutable($object->format(\DATE_RFC3339));
}

$dateTimeErrors = \DateTime::class === $class ? \DateTime::getLastErrors() : \DateTimeImmutable::getLastErrors();
Expand All @@ -104,7 +134,13 @@ public function denormalize($data, $class, string $format = null, array $context
}

try {
return \DateTime::class === $class ? new \DateTime($data, $timezone) : new \DateTimeImmutable($data, $timezone);
$object = new \DateTime($data, $timezone);

if ($preserveContextTimezone) {
$object->setTimezone($timezone);
}

return \DateTime::class === $class ? $object : new \DateTimeImmutable($object->format(\DATE_RFC3339));
} catch (\Exception $e) {
throw new NotNormalizableValueException($e->getMessage(), $e->getCode(), $e);
}
Expand Down Expand Up @@ -152,4 +188,22 @@ private function getTimezone(array $context)

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

private function isPreserveContextTimezone(array $context): bool
{
// Version 5.0 of Symfony/Serializer will always preserve the context timezone, so this method always will return true, unless the timezone equals null.
if (null === $this->getTimezone($context)) {
return false;
}

if (!isset($context[self::PRESERVE_CONTEXT_TIMEZONE]) && !isset($this->defaultContext[self::PRESERVE_CONTEXT_TIMEZONE])) {
@trigger_error('Not setting the boolean "PRESERVE_CONTEXT_TIMEZONE" flag is deprecated. Set the flag to "true" to apply the context timezone consistently, otherwise setting the flag to "false" will preserve default PHP behavior.', E_USER_DEPRECATED);
}

if (!isset($context[self::PRESERVE_CONTEXT_TIMEZONE])) {
return (bool) isset($this->defaultContext[self::PRESERVE_CONTEXT_TIMEZONE]) ? $this->defaultContext[self::PRESERVE_CONTEXT_TIMEZONE] : false;
}

return (bool) isset($context[self::PRESERVE_CONTEXT_TIMEZONE]) ? $context[self::PRESERVE_CONTEXT_TIMEZONE] : false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@ class DateTimeNormalizerTest extends TestCase

protected function setUp()
{
$this->normalizer = new DateTimeNormalizer();
$this->normalizer = new DateTimeNormalizer(
[
DateTimeNormalizer::PRESERVE_CONTEXT_TIMEZONE => false,
]
);
}

public function testSupportsNormalization()
Expand Down Expand Up @@ -180,10 +184,50 @@ public function testDenormalize()
}

public function testDenormalizeUsingTimezonePassedInConstructor()
{

$this->doTestDenormalizeUsingTimezonePassedInConstructor();
}

public function testDenormalizeUsingTimezonePassedInContext()
{
// Test correction of Timezone when timezone information is added in both the date string and the context of the normalizer.
$normalizer = new DateTimeNormalizer(
[
// This is different from Europe times and has NO daylight saving, so tests always pass.
DateTimeNormalizer::TIMEZONE_KEY => 'Australia/Brisbane',
DateTimeNormalizer::PRESERVE_CONTEXT_TIMEZONE => true,
]
);

$this->assertSame('2016-01-28T01:39:26+10:00', $normalizer->denormalize('2016-01-27T16:39:26+01:00', \DateTimeInterface::class)->format(\DATE_RFC3339), 'Non UTC');
$this->assertSame('2016-01-28T01:39:26+10:00', $normalizer->denormalize('2016-01-27T15:39:26+00:00', \DateTime::class)->format(\DATE_RFC3339), 'UTC');
$this->assertSame('2016-01-28T01:39:26+10:00', $normalizer->denormalize('2016-01-28 01:39:26', \DateTime::class)->format(\DATE_RFC3339), 'No timezone in string');
$this->assertSame('2016-01-28T01:39:26+10:00', $normalizer->denormalize('2016-01-28T01:39:26+10:00', \DateTimeInterface::class)->format(\DATE_RFC3339), 'Same timezone as constructor');
$this->assertSame('2016-01-28T01:39:26+10:00', $normalizer->denormalize('@1453909166', \DateTimeImmutable::class)->format(\DATE_RFC3339), 'Timestamp string assumes UTC');
$this->assertSame('2016-01-28T01:39:26+10:00', $normalizer->denormalize('2016-01-27T15:39:26+00:00', \DateTimeImmutable::class, \DATE_RFC3339)->format(\DATE_RFC3339), 'Check format change.');
$this->assertSame('2016-01-28T01:39:26+10:00', $normalizer->denormalize('2016-01-27T15:39:26+00:00', \DateTimeImmutable::class, null, [DateTimeNormalizer::FORMAT_KEY => \DATE_RFC3339])->format(\DATE_RFC3339), 'Check context format denormalization.');

$this->assertSame('2016-01-28T00:39:26+09:00', $normalizer->denormalize('@1453909166', \DateTimeImmutable::class, null, [DateTimeNormalizer::TIMEZONE_KEY => 'Japan'])->format(\DATE_RFC3339), 'Check timezone context change.');

$this->assertSame('2016-01-27T15:39:26+00:00', $normalizer->denormalize('@1453909166', \DateTimeImmutable::class, null, [DateTimeNormalizer::PRESERVE_CONTEXT_TIMEZONE => false])->format(\DATE_RFC3339), 'Should revert to UTC');

$normalizer = new DateTimeNormalizer();
$this->assertSame('2016-01-27T15:39:26+00:00', $normalizer->denormalize('2016-01-27T15:39:26+00:00', \DateTimeInterface::class, null, [DateTimeNormalizer::PRESERVE_CONTEXT_TIMEZONE => false])->format(\DATE_RFC3339), 'Should be UTC');
$this->assertSame('+09:00', $normalizer->denormalize('2016-01-27T16:39:26+01:00', \DateTime::class, null, [DateTimeNormalizer::PRESERVE_CONTEXT_TIMEZONE => true, DateTimeNormalizer::TIMEZONE_KEY => '+09:00'])->getTimezone()->getName(), '+09:00 timezone with context.');
$this->assertSame('2016-01-27T15:39:26+00:00', $normalizer->denormalize('@1453909166', \DateTimeImmutable::class, null, [DateTimeNormalizer::PRESERVE_CONTEXT_TIMEZONE => false])->format(\DATE_RFC3339), 'Timestamp string assumes UTC, and should be UTC');
}

public function testLegacyDenormalizeUsingTimezonePassedInConstructor()
{
$this->doTestDenormalizeUsingTimezonePassedInConstructor(true);
}

private function doTestDenormalizeUsingTimezonePassedInConstructor(bool $legacy = false)
{
$timezone = new \DateTimeZone('Japan');
$expected = new \DateTime('2016/12/01 17:35:00', $timezone);
$normalizer = new DateTimeNormalizer([DateTimeNormalizer::TIMEZONE_KEY => $timezone]);
$normalizer = $legacy ? new DateTimeNormalizer([DateTimeNormalizer::PRESERVE_CONTEXT_TIMEZONE => true], $timezone) : new DateTimeNormalizer([DateTimeNormalizer::TIMEZONE_KEY => $timezone, DateTimeNormalizer::PRESERVE_CONTEXT_TIMEZONE => true]);

$this->assertEquals($expected, $normalizer->denormalize('2016.12.01 17:35:00', \DateTime::class, null, [
DateTimeNormalizer::FORMAT_KEY => 'Y.m.d H:i:s',
Expand All @@ -200,11 +244,12 @@ public function testDenormalizeUsingFormatPassedInContext()
/**
* @dataProvider denormalizeUsingTimezonePassedInContextProvider
*/
public function testDenormalizeUsingTimezonePassedInContext($input, $expected, $timezone, $format = null)
public function testDenormalizeUsingTimezonePassedInDefaultContext($input, $expected, $timezone, $format = null)
{
$actual = $this->normalizer->denormalize($input, \DateTimeInterface::class, null, [
DateTimeNormalizer::TIMEZONE_KEY => $timezone,
DateTimeNormalizer::FORMAT_KEY => $format,
DateTimeNormalizer::PRESERVE_CONTEXT_TIMEZONE => false,
]);

$this->assertEquals($expected, $actual);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -555,7 +555,7 @@ public function testDenomalizeRecursive()
{
$extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]);
$normalizer = new ObjectNormalizer(null, null, null, $extractor);
$serializer = new Serializer([new ArrayDenormalizer(), new DateTimeNormalizer(), $normalizer]);
$serializer = new Serializer([new ArrayDenormalizer(), new DateTimeNormalizer([DateTimeNormalizer::FORMAT_KEY => 'Y-m-d', DateTimeNormalizer::PRESERVE_CONTEXT_TIMEZONE => false]), $normalizer]);

$obj = $serializer->denormalize([
'inner' => ['foo' => 'foo', 'bar' => 'bar'],
Expand Down