Skip to content

Commit e361f26

Browse files
authored
fix: datetime caster with datetime object (#514)
1 parent c09cdf4 commit e361f26

File tree

3 files changed

+9
-0
lines changed

3 files changed

+9
-0
lines changed

src/Tempest/Mapper/src/Casters/DateTimeCaster.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ public static function fromProperty(PropertyReflector $property): DateTimeCaster
3232

3333
public function cast(mixed $input): DateTimeInterface
3434
{
35+
if ($input instanceof DateTimeInterface) {
36+
return $input;
37+
}
38+
3539
if ($this->immutable) {
3640
$date = DateTimeImmutable::createFromFormat($this->format, $input);
3741
} else {

tests/Integration/Mapper/Fixtures/ObjectWithBuiltInCasters.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010

1111
final class ObjectWithBuiltInCasters
1212
{
13+
public DateTimeImmutable $dateTimeObject;
14+
1315
public DateTimeImmutable $dateTimeImmutable;
1416

1517
public DateTime $dateTime;

tests/Integration/Mapper/Mappers/ArrayToObjectMapperTestCase.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace Tests\Tempest\Integration\Mapper\Mappers;
66

7+
use DateTimeImmutable;
78
use InvalidArgumentException;
89
use Tempest\Http\Method;
910
use function Tempest\map;
@@ -64,6 +65,7 @@ public function test_default_values(): void
6465
public function test_built_in_casters(): void
6566
{
6667
$object = map([
68+
'dateTimeObject' => new DateTimeImmutable('2024-01-01 10:10:10'),
6769
'dateTimeImmutable' => '2024-01-01 10:10:10',
6870
'dateTime' => '2024-01-01 10:10:10',
6971
'dateTimeWithFormat' => '01/12/2024 10:10:10',
@@ -72,6 +74,7 @@ public function test_built_in_casters(): void
7274
'int' => '1',
7375
])->to(ObjectWithBuiltInCasters::class);
7476

77+
$this->assertSame('2024-01-01 10:10:10', $object->dateTimeObject->format('Y-m-d H:i:s'));
7578
$this->assertSame('2024-01-01 10:10:10', $object->dateTimeImmutable->format('Y-m-d H:i:s'));
7679
$this->assertSame('2024-01-01 10:10:10', $object->dateTime->format('Y-m-d H:i:s'));
7780
$this->assertSame('2024-12-01 10:10:10', $object->dateTimeWithFormat->format('Y-m-d H:i:s'));

0 commit comments

Comments
 (0)