Skip to content

Commit 0296b72

Browse files
committed
handle DateTimeInterface objects
1 parent f1f940d commit 0296b72

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

system/Entity/Entity.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
use CodeIgniter\Entity\Exceptions\CastException;
3232
use CodeIgniter\I18n\Time;
3333
use DateTime;
34+
use DateTimeInterface;
3435
use Exception;
3536
use JsonSerializable;
3637
use ReturnTypeWillChange;
@@ -374,6 +375,11 @@ private function normalizeValue(mixed $data): mixed
374375
'__class' => $data::class,
375376
'__enum' => $data instanceof BackedEnum ? $data->value : $data->name,
376377
];
378+
} elseif ($data instanceof DateTimeInterface) {
379+
return [
380+
'__class' => $data::class,
381+
'__datetime' => $data->format(DATE_ATOM),
382+
];
377383
} else {
378384
$objectData = get_object_vars($data);
379385
}

tests/system/Entity/EntityTest.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
use CodeIgniter\Test\ReflectionHelper;
2222
use DateTime;
2323
use DateTimeInterface;
24+
use DateTimeZone;
2425
use JsonSerializable;
2526
use PHPUnit\Framework\Attributes\DataProvider;
2627
use PHPUnit\Framework\Attributes\Group;
@@ -2169,4 +2170,32 @@ public function testSyncOriginalWithEnumValues(): void
21692170
$this->assertSame(ColorEnum::class, $colorData['__class']);
21702171
$this->assertSame('GREEN', $colorData['__enum']);
21712172
}
2173+
2174+
public function testHasChangedWithDateTimeInterface(): void
2175+
{
2176+
$entity = new class () extends Entity {
2177+
protected $attributes = [
2178+
'created_at' => null,
2179+
];
2180+
};
2181+
2182+
// Test with Time object
2183+
$entity->created_at = Time::parse('2024-01-01 12:00:00', 'UTC');
2184+
$entity->syncOriginal();
2185+
2186+
$this->assertFalse($entity->hasChanged('created_at'));
2187+
2188+
$entity->created_at = Time::parse('2024-12-31 23:59:59', 'UTC');
2189+
$this->assertTrue($entity->hasChanged('created_at'));
2190+
2191+
$entity->syncOriginal();
2192+
$entity->created_at = Time::parse('2024-12-31 23:59:59', 'UTC');
2193+
$this->assertFalse($entity->hasChanged('created_at'));
2194+
2195+
// Test timezone difference detection
2196+
$entity->created_at = new DateTime('2024-01-01 12:00:00', new DateTimeZone('UTC'));
2197+
$entity->syncOriginal();
2198+
$entity->created_at = new DateTime('2024-01-01 12:00:00', new DateTimeZone('America/New_York'));
2199+
$this->assertTrue($entity->hasChanged('created_at'));
2200+
}
21722201
}

0 commit comments

Comments
 (0)