diff --git a/CHANGELOG.md b/CHANGELOG.md index 6053eb9..d8ebb72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,23 @@ All notable changes to `Serde` will be documented in this file. Updates should follow the [Keep a CHANGELOG](http://keepachangelog.com/) principles. +## Unreleased + +### Added +- Nothing + +### Deprecated +- Nothing + +### Fixed +- A PHP type hint of `DateTimeInterface` will now deserialize to a `DateTimeImmutable` object instead of throwing an error. + +### Removed +- Nothing + +### Security +- Nothing + ## 1.5.0 - 2025-07-15 ### Added diff --git a/README.md b/README.md index fcaa233..0deb392 100644 --- a/README.md +++ b/README.md @@ -566,6 +566,8 @@ Will serialize to this JSON: } ``` +Note that a type of `DateTimeInterface` will deserialize to a `DateTimeImmutable` object. + #### `timezone` The `timezone` argument may be any timezone string legal in PHP, such as `America/Chicago` or `UTC`. If specified, the value will be cast to this timezone first before it is serialized. If not specified, the value will be left in whatever timezone it is in before being serialized. Whether that makes a difference to the output depends on the `format`. diff --git a/src/PropertyHandler/DateTimeExporter.php b/src/PropertyHandler/DateTimeExporter.php index 241436c..d56083c 100644 --- a/src/PropertyHandler/DateTimeExporter.php +++ b/src/PropertyHandler/DateTimeExporter.php @@ -68,7 +68,10 @@ public function importValue(Deserializer $deserializer, Field $field, mixed $sou // an opt-in/out flag to restrict the format on import should be added // to DateField to get used here. Until then, this will do. - return new ($field->phpType)($string); + // If the PHP type is a DateTimeInterface, fulfill that with a DateTimeImmutable. + $type = ($field->phpType === \DateTimeInterface::class) ? \DateTimeImmutable::class : $field->phpType; + + return new ($type)($string); } public function canImport(Field $field, string $format): bool diff --git a/tests/Records/DateTimeInterfaceExample.php b/tests/Records/DateTimeInterfaceExample.php new file mode 100644 index 0000000..c7754d7 --- /dev/null +++ b/tests/Records/DateTimeInterfaceExample.php @@ -0,0 +1,13 @@ + [1, 2, 3]], ), ]; + yield 'datetimeinterface_type' => [ + 'data' => new DateTimeInterfaceExample( + interfaceProperty: new \DateTimeImmutable('2025-12-25 12:34:56.789'), + ), + ]; } public static function value_object_flatten_examples(): \Generator