Merge pull request #920 from TheFrozenFire/feature-SSListEach

API: Add new method "each" to SS_List
This commit is contained in:
Simon Welsh 2012-11-03 02:10:23 -07:00
commit 123a742872
6 changed files with 68 additions and 0 deletions

View File

@ -66,6 +66,18 @@ class ArrayList extends ViewableData implements SS_List, SS_Filterable, SS_Sorta
public function toArray() {
return $this->items;
}
/**
* Walks the list using the specified callback
*
* @param callable $callback
* @return DataList
*/
public function each($callback) {
foreach($this as $item) {
$callback($item);
}
}
public function debug() {
$val = "<h2>" . $this->class . "</h2><ul>";

View File

@ -650,6 +650,20 @@ class DataList extends ViewableData implements SS_List, SS_Filterable, SS_Sortab
return $result;
}
/**
* Walks the list using the specified callback
*
* @param callable $callback
* @return DataList
*/
public function each($callback) {
foreach($this as $row) {
$callback($row);
}
return $this;
}
public function debug() {
$val = "<h2>" . $this->class . "</h2><ul>";

View File

@ -77,4 +77,12 @@ interface SS_List extends ArrayAccess, Countable, IteratorAggregate {
* @return array
*/
public function column($colName = "ID");
/**
* Walks the list using the specified callback
*
* @param callable $callback
* @return mixed
*/
public function each($callback);
}

View File

@ -103,6 +103,10 @@ abstract class SS_ListDecorator extends ViewableData implements SS_List, SS_Sort
public function column($value = 'ID') {
return $this->list->column($value);
}
public function each($callback) {
return $this->list->each($callback);
}
public function canSortBy($by) {
return $this->list->canSortBy($by);

View File

@ -60,6 +60,21 @@ class ArrayListTest extends SapphireTest {
array('First' => 'ThirdFirst', 'Second' => 'ThirdSecond')
));
}
public function testEach() {
$list = new ArrayList(array(1, 2, 3));
$count = 0;
$test = $this;
$list->each(function($item) use (&$count, $test) {
$count++;
$test->assertTrue(is_int($item));
});
$this->assertEquals($list->Count(), $count);
}
public function testLimit() {
$list = new ArrayList(array(

View File

@ -179,6 +179,21 @@ class DataListTest extends SapphireTest {
$this->assertEquals($otherExpected, $otherMap);
}
public function testEach() {
$list = DataObjectTest_TeamComment::get();
$count = 0;
$test = $this;
$list->each(function($item) use (&$count, $test) {
$count++;
$test->assertTrue(is_a($item, "DataObjectTest_TeamComment"));
});
$this->assertEquals($list->Count(), $count);
}
public function testFilter() {
// coming soon!
}