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
This commit is contained in:
Russell 2015-05-21 15:30:19 +12:00 committed by Loz Calver
parent 7c09f82770
commit 51722e3d12
2 changed files with 28 additions and 0 deletions

View File

@ -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) {

View File

@ -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();