From 76fba413e18c583a793a29ca9651fc9af3de59d1 Mon Sep 17 00:00:00 2001 From: Albert Chen Date: Thu, 13 Nov 2025 15:51:45 +0800 Subject: [PATCH] feat: implement update function in DataObject --- .../Database/Eloquent/Casts/AsDataObject.php | 2 -- src/support/src/DataObject.php | 15 ++++++++ tests/Support/DataObjectTest.php | 34 +++++++++++++++++++ 3 files changed, 49 insertions(+), 2 deletions(-) diff --git a/src/core/src/Database/Eloquent/Casts/AsDataObject.php b/src/core/src/Database/Eloquent/Casts/AsDataObject.php index 7415dbb4..b52b8601 100644 --- a/src/core/src/Database/Eloquent/Casts/AsDataObject.php +++ b/src/core/src/Database/Eloquent/Casts/AsDataObject.php @@ -10,8 +10,6 @@ class AsDataObject implements CastsAttributes { - protected static $reflectionCache = []; - public function __construct( protected string $argument ) { diff --git a/src/support/src/DataObject.php b/src/support/src/DataObject.php index 6629a93a..0ed69243 100644 --- a/src/support/src/DataObject.php +++ b/src/support/src/DataObject.php @@ -488,6 +488,21 @@ protected static function getReversedPropertyMap(): array ); } + /** + * Update the object properties with the provided data array. + */ + public function update(array $data): static + { + $properties = static::getPropertyMap(); + foreach ($data as $key => $value) { + $this->{$properties[$key]} = $value; + } + + $this->refresh(); + + return $this; + } + /** * Check if the offset exists. */ diff --git a/tests/Support/DataObjectTest.php b/tests/Support/DataObjectTest.php index 2746e1cb..be14c547 100644 --- a/tests/Support/DataObjectTest.php +++ b/tests/Support/DataObjectTest.php @@ -80,6 +80,40 @@ public function testMutationAndRefreshData(): void $this->assertNull($object->nullableValue); } + /** + * Test mutating a data object and refreshing data. + */ + public function testUpdate(): void + { + $data = [ + 'string_value' => 'test', + 'int_value' => '42', // String that should be converted to int + 'float_value' => '3.14', // String that should be converted to float + 'bool_value' => 1, // Int that should be converted to bool + 'array_value' => ['item1', 'item2'], + 'object_value' => new stdClass(), + ]; + + $object = TestDataObject::make($data); + $object->update([ + 'string_value' => 'test_changed', + 'int_value' => 100, + 'float_value' => 6.28, + 'bool_value' => false, + 'array_value' => ['item3', 'item4'], + ]); + + $this->assertInstanceOf(TestDataObject::class, $object); + $this->assertSame('test_changed', $object->stringValue); + $this->assertSame(100, $object->intValue); + $this->assertSame(6.28, $object->floatValue); + $this->assertFalse($object->boolValue); + $this->assertSame(['item3', 'item4'], $object->arrayValue); + $this->assertInstanceOf(stdClass::class, $object->objectValue); + $this->assertSame('default value', $object->withDefaultValue); + $this->assertNull($object->nullableValue); + } + /** * Test creating a data object with massing data. */