Skip to content

Commit 165666a

Browse files
committed
fix: make Entity::toRawArray datetime conversion BC and preserve microseconds
1 parent 3eceb0c commit 165666a

5 files changed

Lines changed: 125 additions & 8 deletions

File tree

‎system/DataCaster/Cast/TimestampCast.php‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
namespace CodeIgniter\DataCaster\Cast;
1515

1616
use CodeIgniter\I18n\Time;
17+
use DateTimeInterface;
18+
use Exception;
1719

1820
/**
1921
* Class TimestampCast
@@ -40,7 +42,15 @@ public static function set(
4042
array $params = [],
4143
?object $helper = null,
4244
): int {
43-
if (! $value instanceof Time) {
45+
if (is_string($value)) {
46+
try {
47+
$value = Time::parse($value);
48+
} catch (Exception) {
49+
self::invalidTypeValueError($value);
50+
}
51+
}
52+
53+
if (! $value instanceof DateTimeInterface) {
4454
self::invalidTypeValueError($value);
4555
}
4656

‎system/Entity/Entity.php‎

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -336,15 +336,27 @@ public function toRawArray(bool $onlyChanged = false, bool $recursive = false):
336336
}
337337
}
338338

339-
// Convert DateTime objects to string for user-facing calls
339+
// Convert DateTime objects to string for user-facing calls (only for dates/datetime cast fields)
340340
if (! $recursive) {
341-
$result = array_map(static function ($value) {
341+
foreach ($result as $key => $value) {
342342
if ($value instanceof DateTimeInterface) {
343-
return method_exists($value, '__toString') ? (string) $value : $value->format('Y-m-d H:i:s');
344-
}
343+
$isDate = in_array($key, $this->dates, true);
344+
if (! $isDate && isset($this->casts[$key])) {
345+
$cast = $this->casts[$key];
346+
if (str_contains($cast, 'datetime')) {
347+
$isDate = true;
348+
}
349+
}
345350

346-
return $value;
347-
}, $result);
351+
if ($isDate) {
352+
if ((int) $value->format('u') > 0) {
353+
$result[$key] = $value->format('Y-m-d H:i:s.u');
354+
} else {
355+
$result[$key] = method_exists($value, '__toString') ? (string) $value : $value->format('Y-m-d H:i:s');
356+
}
357+
}
358+
}
359+
}
348360
}
349361

350362
return $result;

‎tests/system/DataConverter/DataConverterTest.php‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
use Closure;
1717
use CodeIgniter\DataCaster\Exceptions\CastException;
18+
use CodeIgniter\Entity\Entity;
1819
use CodeIgniter\HTTP\URI;
1920
use CodeIgniter\I18n\Time;
2021
use CodeIgniter\Test\CIUnitTestCase;
@@ -877,6 +878,44 @@ public function testExtractWithClosure(): void
877878
], $array);
878879
}
879880

881+
public function testExtractEntityWithTimestampCast(): void
882+
{
883+
$converter = $this->createDataConverter([
884+
'updated_at' => 'timestamp',
885+
]);
886+
887+
$entity = new class () extends Entity {
888+
protected $dates = [];
889+
};
890+
$entity->injectRawData([
891+
'updated_at' => Time::createFromTimestamp(1_784_092_299),
892+
]);
893+
894+
$data = $converter->extract($entity);
895+
896+
$this->assertSame(1_784_092_299, $data['updated_at']);
897+
}
898+
899+
public function testExtractEntityPreservesMicrosecondsWithDatetimeCast(): void
900+
{
901+
$converter = $this->createDataConverter(
902+
['updated_at' => 'datetime[us]'],
903+
[],
904+
db_connect(),
905+
);
906+
907+
$entity = new class () extends Entity {
908+
protected $dates = [];
909+
};
910+
$entity->injectRawData([
911+
'updated_at' => Time::createFromFormat('Y-m-d H:i:s.u', '2026-07-15 00:00:01.123456'),
912+
]);
913+
914+
$data = $converter->extract($entity);
915+
916+
$this->assertSame('2026-07-15 00:00:01.123456', $data['updated_at']);
917+
}
918+
880919
/**
881920
* @param array<string, string> $types
882921
* @param array<string, mixed> $data

‎tests/system/Entity/EntityTest.php‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1543,6 +1543,62 @@ public function testToRawArrayRecursiveWithMixedAttributes(): void
15431543
$this->assertIsString($result2['created_at']);
15441544
}
15451545

1546+
public function testToRawArrayDoesNotConvertDateTimeWhenNotDeclaredInDatesOrCasts(): void
1547+
{
1548+
$entity = new class () extends Entity {
1549+
protected $attributes = [
1550+
'custom_date' => null,
1551+
];
1552+
protected $dates = [];
1553+
protected $casts = [];
1554+
};
1555+
1556+
$entity->custom_date = Time::parse('2024-08-20 16:45:00');
1557+
1558+
$result = $entity->toRawArray();
1559+
$this->assertInstanceOf(Time::class, $result['custom_date']);
1560+
}
1561+
1562+
public function testToRawArrayRespectsCustomDateTimeStringConversion(): void
1563+
{
1564+
$customDateTime = new class ('2024-08-20 16:45:00') extends DateTime {
1565+
public function __toString(): string
1566+
{
1567+
return 'custom-formatted-date';
1568+
}
1569+
};
1570+
1571+
$entity = new class () extends Entity {
1572+
protected $attributes = [
1573+
'created_at' => null,
1574+
];
1575+
protected $dates = [];
1576+
protected $casts = [
1577+
'created_at' => 'datetime',
1578+
];
1579+
};
1580+
1581+
$entity->created_at = $customDateTime;
1582+
1583+
$result = $entity->toRawArray();
1584+
$this->assertSame('custom-formatted-date', $result['created_at']);
1585+
}
1586+
1587+
public function testToRawArrayConvertsNativeDateTimeToString(): void
1588+
{
1589+
$entity = new class () extends Entity {
1590+
protected $attributes = [
1591+
'created_at' => null,
1592+
];
1593+
protected $dates = ['created_at'];
1594+
};
1595+
1596+
$entity->created_at = new DateTime('2024-08-20 16:45:00');
1597+
1598+
$result = $entity->toRawArray();
1599+
$this->assertSame('2024-08-20 16:45:00', $result['created_at']);
1600+
}
1601+
15461602
public function testFilledConstruction(): void
15471603
{
15481604
$data = [

‎user_guide_src/source/changelogs/v4.7.5.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ Deprecations
3030
Bugs Fixed
3131
**********
3232

33-
- **Entity:** Fixed a bug where ``toRawArray()`` returned ``Time`` objects instead of ISO-8601 strings for date fields.
33+
- **Entity:** Fixed a bug where ``toRawArray()`` returned ``Time`` objects instead of strings for date fields.
3434

3535
- **Logger:** Fixed a bug where interpolating a log message with array or non-stringable context values could raise PHP warnings or errors.
3636

0 commit comments

Comments
 (0)