Skip to content

Commit abe6991

Browse files
committed
fix: handle pure DateTime objects properly in toRawArray
1 parent 8945d42 commit abe6991

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

‎system/Entity/Entity.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ public function toRawArray(bool $onlyChanged = false, bool $recursive = false):
235235
$convert = static function ($value) use (&$convert, $recursive) {
236236
// Always convert DateTime objects to string for raw output
237237
if ($value instanceof DateTimeInterface) {
238-
return (string) $value;
238+
return method_exists($value, '__toString') ? (string) $value : $value->format('Y-m-d H:i:s');
239239
}
240240

241241
if (! $recursive) {

‎tests/system/Entity/EntityTest.php‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,23 @@ public function testToRawArrayConvertsDateTimeToString(): void
402402
$this->assertInstanceOf(Time::class, $array['updated_at']);
403403
}
404404

405+
public function testToRawArrayConvertsStandardDateTimeToString(): void
406+
{
407+
$entity = new class () extends Entity {
408+
protected $attributes = [
409+
'my_date' => null,
410+
];
411+
protected $dates = [];
412+
};
413+
414+
$entity->my_date = new \DateTime('2023-12-12 12:12:12');
415+
416+
$raw = $entity->toRawArray();
417+
418+
$this->assertIsString($raw['my_date']);
419+
$this->assertSame('2023-12-12 12:12:12', $raw['my_date']);
420+
}
421+
405422
public function testCastInteger(): void
406423
{
407424
$entity = $this->getCastEntity();

0 commit comments

Comments
 (0)