diff --git a/model/UnsavedRelationList.php b/model/UnsavedRelationList.php index 2a7ef640d..35aee6049 100644 --- a/model/UnsavedRelationList.php +++ b/model/UnsavedRelationList.php @@ -199,6 +199,26 @@ class UnsavedRelationList extends ArrayList { $this->addMany($idList); } + /** + * Returns an array with both the keys and values set to the IDs of the records in this list. + * + * Does not return the IDs for unsaved DataObjects + */ + public function getIDList() { + // Get a list of IDs of our current items - if it's not a number then object then assume it's a DO. + $ids = array_map(function($obj) { + return is_numeric($obj) ? $obj : $obj->ID; + }, $this->items); + + // Strip out duplicates and anything resolving to False. + $ids = array_filter(array_unique($ids)); + + // Change the array from (1, 2, 3) to (1 => 1, 2 => 2, 3 => 3) + if ($ids) $ids = array_combine($ids, $ids); + + return $ids; + } + /** * Returns the first item in the list * @@ -294,10 +314,6 @@ class UnsavedRelationList extends ArrayList { throw new LogicException(__FUNCTION__ . " can't be called on an UnsavedRelationList."); } - public function getIDList() { - throw new LogicException(__FUNCTION__ . " can't be called on an UnsavedRelationList."); - } - public function getRange($offset, $length) { throw new LogicException(__FUNCTION__ . " can't be called on an UnsavedRelationList."); } diff --git a/tests/model/UnsavedRelationListTest.php b/tests/model/UnsavedRelationListTest.php index 57f011eb6..c2968d85b 100644 --- a/tests/model/UnsavedRelationListTest.php +++ b/tests/model/UnsavedRelationListTest.php @@ -157,6 +157,32 @@ class UnsavedRelationListTest extends SapphireTest { array('Name' => 'C', 'Number' => 3) ), $object->Siblings()); } + + public function testGetIDList() { + $object = new UnsavedRelationListTest_DataObject; + + $children = $object->Children(); + $this->assertEquals($children->getIDList(), array()); + $children->add($child1 = new UnsavedRelationListTest_DataObject(array('Name' => 'A'))); + $children->add($child2 = new UnsavedRelationListTest_DataObject(array('Name' => 'B'))); + $children->add($child3 = new UnsavedRelationListTest_DataObject(array('Name' => 'C'))); + $children->add($child1); + + $this->assertEquals($children->getIDList(), array()); + + $child1->write(); + $this->assertEquals($children->getIDList(), array( + $child1->ID => $child1->ID + )); + + $child2->write(); + $child3->write(); + $this->assertEquals($children->getIDList(), array( + $child1->ID => $child1->ID, + $child2->ID => $child2->ID, + $child3->ID => $child3->ID + )); + } } class UnsavedRelationListTest_DataObject extends DataObject implements TestOnly {