Skip to content
Merged
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
2 changes: 0 additions & 2 deletions src/core/src/Database/Eloquent/Casts/AsDataObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@

class AsDataObject implements CastsAttributes
{
protected static $reflectionCache = [];

public function __construct(
protected string $argument
) {
Expand Down
15 changes: 15 additions & 0 deletions src/support/src/DataObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down
34 changes: 34 additions & 0 deletions tests/Support/DataObjectTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down