-
-
Notifications
You must be signed in to change notification settings - Fork 9.7k
[Serializer] Add support for denormalizing invalid datetime without throwing an exception #42236
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
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
[Serializer] Add support for denormalizing invalid datetime without t…
…hrowing an exception
- Loading branch information
commit 364bd7f4fcb437b9a2d99362a37575f8b95fb4b6
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -17,17 +17,21 @@ | |
/** | ||
* Normalizes an object implementing the {@see \DateTimeInterface} to a date string. | ||
* Denormalizes a date string to an instance of {@see \DateTime} or {@see \DateTimeImmutable}. | ||
* The denormalization may return the raw data if invalid according to the value of $context[self::THROW_EXCEPTION_ON_INVALID_KEY]. | ||
* | ||
* @author Kévin Dunglas <[email protected]> | ||
*/ | ||
class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface, CacheableSupportsMethodInterface | ||
{ | ||
public const FORMAT_KEY = 'datetime_format'; | ||
public const TIMEZONE_KEY = 'datetime_timezone'; | ||
public const THROW_EXCEPTION_ON_INVALID_KEY = 'throw_exception_on_invalid_key'; | ||
|
||
private $defaultContext = [ | ||
self::FORMAT_KEY => \DateTime::RFC3339, | ||
self::TIMEZONE_KEY => null, | ||
// BC layer to be moved to "false" in 6.0 | ||
self::THROW_EXCEPTION_ON_INVALID_KEY => null, | ||
]; | ||
|
||
private const SUPPORTED_TYPES = [ | ||
|
@@ -39,6 +43,10 @@ class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface, | |
public function __construct(array $defaultContext = []) | ||
{ | ||
$this->defaultContext = array_merge($this->defaultContext, $defaultContext); | ||
|
||
if (null === $this->defaultContext[self::THROW_EXCEPTION_ON_INVALID_KEY]) { | ||
trigger_deprecation('symfony/serializer', '5.4', 'The key context "%s" of "%s" must be defined. The value will be "false" in Symfony 6.0.', self::THROW_EXCEPTION_ON_INVALID_KEY, __CLASS__); | ||
} | ||
} | ||
|
||
/** | ||
|
@@ -77,15 +85,22 @@ public function supportsNormalization($data, string $format = null) | |
* {@inheritdoc} | ||
* | ||
* @throws NotNormalizableValueException | ||
* | ||
* @return \DateTimeInterface | ||
*/ | ||
public function denormalize($data, string $type, string $format = null, array $context = []) | ||
{ | ||
$dateTimeFormat = $context[self::FORMAT_KEY] ?? null; | ||
$throwExceptionOnInvalid = $context[self::THROW_EXCEPTION_ON_INVALID_KEY] ?? $this->defaultContext[self::THROW_EXCEPTION_ON_INVALID_KEY]; | ||
// BC layer to be removed in 6.0 | ||
if (null === $throwExceptionOnInvalid) { | ||
$throwExceptionOnInvalid = true; | ||
} | ||
$timezone = $this->getTimezone($context); | ||
|
||
if (null === $data || (\is_string($data) && '' === trim($data))) { | ||
if (!$throwExceptionOnInvalid) { | ||
return $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.'); | ||
} | ||
|
||
|
@@ -98,12 +113,20 @@ public function denormalize($data, string $type, string $format = null, array $c | |
|
||
$dateTimeErrors = \DateTime::class === $type ? \DateTime::getLastErrors() : \DateTimeImmutable::getLastErrors(); | ||
|
||
if (!$throwExceptionOnInvalid) { | ||
return $data; | ||
} | ||
|
||
throw new NotNormalizableValueException(sprintf('Parsing datetime string "%s" using format "%s" resulted in %d errors: ', $data, $dateTimeFormat, $dateTimeErrors['error_count'])."\n".implode("\n", $this->formatDateTimeErrors($dateTimeErrors['errors']))); | ||
} | ||
|
||
try { | ||
return \DateTime::class === $type ? new \DateTime($data, $timezone) : new \DateTimeImmutable($data, $timezone); | ||
} catch (\Exception $e) { | ||
if (!$throwExceptionOnInvalid) { | ||
return $data; | ||
} | ||
|
||
throw new NotNormalizableValueException($e->getMessage(), $e->getCode(), $e); | ||
} | ||
} | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.