mirror of
https://github.com/silverstripe/silverstripe-framework
synced 2024-10-22 12:05:37 +00:00
Merge pull request #2293 from robert-h-curry/empty-arraylist
Preempt fatal errors when making some function calls on an empty ArrayList
This commit is contained in:
commit
c7bdfcd76a
@ -404,7 +404,11 @@ class ArrayList extends ViewableData implements SS_List, SS_Filterable, SS_Sorta
|
||||
* It works by checking the fields available in the first record of the list.
|
||||
*/
|
||||
public function canFilterBy($by) {
|
||||
return array_key_exists($by, $this->first());
|
||||
$firstRecord = $this->first();
|
||||
if ($firstRecord === false) {
|
||||
return false;
|
||||
}
|
||||
return array_key_exists($by, $firstRecord);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -460,7 +464,11 @@ class ArrayList extends ViewableData implements SS_List, SS_Filterable, SS_Sorta
|
||||
}
|
||||
|
||||
public function byID($id) {
|
||||
return $this->filter("ID", $id)->First();
|
||||
$firstElement = $this->filter("ID", $id)->first();
|
||||
if ($firstElement === false) {
|
||||
return null;
|
||||
}
|
||||
return $firstElement;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -599,6 +599,48 @@ class ArrayListTest extends SapphireTest {
|
||||
);
|
||||
$this->assertEquals($expected, $list->toArray());
|
||||
}
|
||||
|
||||
public function testCanFilterBy() {
|
||||
$list = new ArrayList(array(
|
||||
array('Name' => 'Steve'),
|
||||
array('Name' => 'Bob'),
|
||||
array('Name' => 'John')
|
||||
));
|
||||
|
||||
$this->assertTrue($list->canFilterBy('Name'));
|
||||
$this->assertFalse($list->canFilterBy('Age'));
|
||||
}
|
||||
|
||||
public function testCanFilterByEmpty() {
|
||||
$list = new ArrayList();
|
||||
|
||||
$this->assertFalse($list->canFilterBy('Name'));
|
||||
$this->assertFalse($list->canFilterBy('Age'));
|
||||
}
|
||||
|
||||
public function testByID() {
|
||||
$list = new ArrayList(array(
|
||||
array('ID' => 1, 'Name' => 'Steve'),
|
||||
array('ID' => 2, 'Name' => 'Bob'),
|
||||
array('ID' => 3, 'Name' => 'John')
|
||||
));
|
||||
|
||||
$element = $list->byID(1);
|
||||
$this->assertEquals($element['Name'], 'Steve');
|
||||
|
||||
$element = $list->byID(2);
|
||||
$this->assertEquals($element['Name'], 'Bob');
|
||||
|
||||
$element = $list->byID(4);
|
||||
$this->assertNull($element);
|
||||
}
|
||||
|
||||
public function testByIDEmpty() {
|
||||
$list = new ArrayList();
|
||||
|
||||
$element = $list->byID(1);
|
||||
$this->assertNull($element);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
Loading…
x
Reference in New Issue
Block a user