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

@ -67,6 +67,18 @@ class ArrayList extends ViewableData implements SS_List, SS_Filterable, SS_Sorta
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>";
foreach($this->toNestedArray() as $item) {

View File

@ -651,6 +651,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

@ -104,6 +104,10 @@ abstract class SS_ListDecorator extends ViewableData implements SS_List, SS_Sort
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

@ -61,6 +61,21 @@ class ArrayListTest extends SapphireTest {
));
}
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(
array('Key' => 1), array('Key' => 2), array('Key' => 3)

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!
}