From 51722e3d12481056e2ede1083ce5c89b16a7da8d Mon Sep 17 00:00:00 2001 From: Russell Date: Thu, 21 May 2015 15:30:19 +1200 Subject: [PATCH] DataObject accept arrays or stdClass The constructor of DataObject can take an array or stdClass for $record. However, it is access as an array [here](https://github.com/silverstripe/silverstripe-framework/blob/3.1/model/DataObject.php#L416) and [here](https://github.com/silverstripe/silverstripe-framework/blob/3.1/model/DataObject.php#L431) This pull request ensures $record is an array after validation --- model/DataObject.php | 4 ++++ tests/model/DataObjectTest.php | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/model/DataObject.php b/model/DataObject.php index 09ac68d66..d2db29b0c 100644 --- a/model/DataObject.php +++ b/model/DataObject.php @@ -400,6 +400,10 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity $record = null; } + if(is_a($record, "stdClass")) { + $record = (array)$record; + } + // Set $this->record to $record, but ignore NULLs $this->record = array(); foreach($record as $k => $v) { diff --git a/tests/model/DataObjectTest.php b/tests/model/DataObjectTest.php index f4b7507ad..73fbe33ec 100644 --- a/tests/model/DataObjectTest.php +++ b/tests/model/DataObjectTest.php @@ -53,6 +53,30 @@ class DataObjectTest extends SapphireTest { $this->assertEquals('Comment', key($dbFields), 'DataObject::db returns fields in correct order'); } + public function testConstructAcceptsValues() { + // Values can be an array... + $player = new DataObjectTest_Player(array( + 'FirstName' => 'James', + 'Surname' => 'Smith' + )); + + $this->assertEquals('James', $player->FirstName); + $this->assertEquals('Smith', $player->Surname); + + // ... or a stdClass inst + $data = new stdClass(); + $data->FirstName = 'John'; + $data->Surname = 'Doe'; + $player = new DataObjectTest_Player($data); + + $this->assertEquals('John', $player->FirstName); + $this->assertEquals('Doe', $player->Surname); + + // IDs should be stored as integers, not strings + $player = new DataObjectTest_Player(array('ID' => '5')); + $this->assertSame(5, $player->ID); + } + public function testValidObjectsForBaseFields() { $obj = new DataObjectTest_ValidatedObject();