diff --git a/model/ArrayList.php b/model/ArrayList.php index 5a49bc1d8..d2fc2a156 100644 --- a/model/ArrayList.php +++ b/model/ArrayList.php @@ -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; } /** diff --git a/tests/model/ArrayListTest.php b/tests/model/ArrayListTest.php index bbb57e75e..9953c5200 100644 --- a/tests/model/ArrayListTest.php +++ b/tests/model/ArrayListTest.php @@ -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); + } } /**