Skip to content

Commit

Permalink
Fixed DateTime deserialization for DateTimeImmutable
Browse files Browse the repository at this point in the history
  • Loading branch information
ddebowczyk committed Oct 5, 2024
1 parent 61b212c commit 6e08178
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 8 deletions.
2 changes: 1 addition & 1 deletion examples/A05_Extras/TranscriptionToTasks/run.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ enum Role : string {
class Task {
public string $title;
public string $description;
public DateTime $dueDate;
public DateTimeImmutable $dueDate;
public Role $owner;
public TaskStatus $status;
}
Expand Down
15 changes: 9 additions & 6 deletions src/Deserialization/Deserializers/FlexibleDateDenormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;

Expand All @@ -14,30 +15,32 @@ public function denormalize($data, string $type, string $format = null, array $c
throw new NotNormalizableValueException('The data is not a string, it cannot be converted to a DateTime.');
}

$date = $this->parseDate($data);
$output = $this->parseDate($data);

if ($date === false) {
if ($output === false) {
throw new NotNormalizableValueException('The date string could not be parsed.');
}

return $date;
return $output;
}

public function getSupportedTypes(?string $format): array {
return [
DateTime::class => true,
DateTimeInterface::class => true,
DateTimeImmutable::class => true,
DateTime::class => true,
];
}

public function supportsDenormalization($data, string $type, string $format = null, array $context = []): bool {
return in_array($type, [
DateTime::class,
DateTimeInterface::class,
DateTimeImmutable::class,
DateTime::class,
]);
}

private function parseDate(string $dateString) {
private function parseDate(string $dateString) : DateTimeImmutable|DateTime|false {
$formats = [
'Y-m-d\TH:i:s.uP', // ISO8601 with microseconds
'Y-m-d\TH:i:sP', // ISO8601
Expand Down
2 changes: 1 addition & 1 deletion src/Deserialization/Deserializers/SymfonyDeserializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,8 @@ protected function defaultSerializer(PropertyInfoExtractor $typeExtractor) : Ser
normalizers: [
new FlexibleDateDenormalizer(),
new BackedEnumNormalizer(),
new PropertyNormalizer(propertyTypeExtractor: $typeExtractor),
new ObjectNormalizer(propertyTypeExtractor: $typeExtractor),
new PropertyNormalizer(propertyTypeExtractor: $typeExtractor),
new GetSetMethodNormalizer(propertyTypeExtractor: $typeExtractor),
new ArrayDenormalizer(),
],
Expand Down

0 comments on commit 6e08178

Please sign in to comment.