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:
Will Rossiter 2013-08-17 16:53:48 -07:00
commit c7bdfcd76a
2 changed files with 52 additions and 2 deletions

View File

@ -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. * It works by checking the fields available in the first record of the list.
*/ */
public function canFilterBy($by) { 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) { public function byID($id) {
return $this->filter("ID", $id)->First(); $firstElement = $this->filter("ID", $id)->first();
if ($firstElement === false) {
return null;
}
return $firstElement;
} }
/** /**

View File

@ -599,6 +599,48 @@ class ArrayListTest extends SapphireTest {
); );
$this->assertEquals($expected, $list->toArray()); $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);
}
} }
/** /**