Skip to content

Commit

Permalink
Merge pull request #11085 from kinglozzer/11083-unsaved-relationlist-bug
Browse files Browse the repository at this point in the history
FIX: UnsavedRelationList first/last to return null if list is empty (fixes #11083)
  • Loading branch information
GuySartorelli authored Dec 4, 2023
2 parents 6d90384 + 40b888e commit 6698e5a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/ORM/UnsavedRelationList.php
Original file line number Diff line number Diff line change
Expand Up @@ -239,11 +239,11 @@ public function getIDList()
*/
public function first()
{
$item = reset($this->items);
$item = reset($this->items) ?: null;
if (is_numeric($item)) {
$item = DataObject::get_by_id($this->dataClass, $item);
}
if (!empty($this->extraFields[key($this->items)])) {
if ($item && !empty($this->extraFields[key($this->items)])) {
$item->update($this->extraFields[key($this->items)]);
}
return $item;
Expand All @@ -256,8 +256,11 @@ public function first()
*/
public function last()
{
$item = end($this->items);
if (!empty($this->extraFields[key($this->items)])) {
$item = end($this->items) ?: null;
if (is_numeric($item)) {
$item = DataObject::get_by_id($this->dataClass, $item);
}
if ($item && !empty($this->extraFields[key($this->items)])) {
$item->update($this->extraFields[key($this->items)]);
}
return $item;
Expand Down
16 changes: 16 additions & 0 deletions tests/php/ORM/UnsavedRelationListTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -310,4 +310,20 @@ public function testColumn()
]
);
}

public function testFirstAndLast()
{
$object = new UnsavedRelationListTest\TestObject();
$children = $object->Children();

$this->assertNull($children->first(), 'Empty UnsavedRelationList should return null for first item.');
$this->assertNull($children->last(), 'Empty UnsavedRelationList should return null for last item.');

$children->add($firstChild = $this->objFromFixture(UnsavedRelationListTest\TestObject::class, 'ObjectA'));
$children->add($this->objFromFixture(UnsavedRelationListTest\TestObject::class, 'ObjectB'));
$children->add($lastChild = $this->objFromFixture(UnsavedRelationListTest\TestObject::class, 'ObjectC'));

$this->assertEquals($firstChild, $children->first(), 'Incorrect first item in UnsavedRelationList.');
$this->assertEquals($lastChild, $children->last(), 'Incorrect last item in UnsavedRelationList.');
}
}

0 comments on commit 6698e5a

Please sign in to comment.