Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions system/Entity/Entity.php
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,11 @@
public function toRawArray(bool $onlyChanged = false, bool $recursive = false): array
{
$convert = static function ($value) use (&$convert, $recursive) {
// Always convert DateTime objects to string for raw output
if ($value instanceof DateTimeInterface) {
return (string) $value;

Check failure on line 238 in system/Entity/Entity.php

View workflow job for this annotation

GitHub Actions / PHP Static Analysis

Cannot cast DateTimeInterface to string.
}

if (! $recursive) {
return $value;
}
Expand Down Expand Up @@ -261,9 +266,7 @@

// When returning everything
if (! $onlyChanged) {
return $recursive
? array_map($convert, $this->attributes)
: $this->attributes;
return array_map($convert, $this->attributes);
}

// When filtering by changed values only
Expand Down Expand Up @@ -335,7 +338,7 @@
}

// non-recursive changed value
$return[$key] = $value;
$return[$key] = $convert($value);
}

return $return;
Expand Down
35 changes: 35 additions & 0 deletions tests/system/Entity/EntityTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,41 @@ public function testDateMutationTimeToTime(): void
$this->assertCloseEnoughString($dt->format('Y-m-d H:i:s'), $time->format('Y-m-d H:i:s'));
}

public function testToRawArrayConvertsDateTimeToString(): void
{
$entity = new class () extends Entity {
protected $attributes = [
'created_at' => null,
'updated_at' => null,
];
protected $original = [
'created_at' => null,
'updated_at' => null,
];
};

$entity->created_at = '2023-12-12 12:12:12';
$entity->updated_at = '2023-12-13 13:13:13';

$raw = $entity->toRawArray();

// toRawArray() should return primitive types, not objects
$this->assertIsString($raw['created_at']);
$this->assertSame('2023-12-12 12:12:12', $raw['created_at']);
$this->assertIsString($raw['updated_at']);
$this->assertSame('2023-12-13 13:13:13', $raw['updated_at']);

// Attributes themselves should still contain Time objects
$attrs = $this->getPrivateProperty($entity, 'attributes');
$this->assertInstanceOf(Time::class, $attrs['created_at']);
$this->assertInstanceOf(Time::class, $attrs['updated_at']);

// toArray() should still return Time objects (no regression)
$array = $entity->toArray();
$this->assertInstanceOf(Time::class, $array['created_at']);
$this->assertInstanceOf(Time::class, $array['updated_at']);
}

public function testCastInteger(): void
{
$entity = $this->getCastEntity();
Expand Down
Loading