Preempt fatal errors when making some function calls on an empty ArrayList

The function "first" on ArrayList uses the PHP function "reset", which
returns false if there aren't any elements in the array. Two functions
inside ArrayList use this function, "canFilterBy" and "byID". I've
changed these functions to catch the possibility of a false return from
first().
This commit is contained in:
Robert Curry 2013-08-05 15:43:35 +12:00
parent c5442810cf
commit d69520bd70
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.
*/
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;
}
/**

View File

@ -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);
}
}
/**