From d69520bd70746dce66a0d289cf72464046c165eb Mon Sep 17 00:00:00 2001 From: Robert Curry Date: Mon, 5 Aug 2013 15:43:35 +1200 Subject: [PATCH] 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(). --- model/ArrayList.php | 12 ++++++++-- tests/model/ArrayListTest.php | 42 +++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 2 deletions(-) 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); + } } /**