2011-12-26 09:48:53 +01:00
|
|
|
<?php
|
|
|
|
/**
|
|
|
|
* A list decorator that allows a list to be grouped into sub-lists by common
|
|
|
|
* values of a field.
|
|
|
|
*
|
2012-04-12 08:02:46 +02:00
|
|
|
* @package framework
|
2011-12-26 09:48:53 +01:00
|
|
|
* @subpackage model
|
|
|
|
*/
|
|
|
|
class GroupedList extends SS_ListDecorator {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param string $index
|
2012-06-23 00:32:43 +02:00
|
|
|
* @return array
|
2011-12-26 09:48:53 +01:00
|
|
|
*/
|
|
|
|
public function groupBy($index) {
|
|
|
|
$result = array();
|
|
|
|
|
|
|
|
foreach ($this->list as $item) {
|
2013-12-21 03:15:55 +01:00
|
|
|
/* if $item is an Object, $index can be a method or a value,
|
|
|
|
* if $item is an array, $index is used as the index */
|
|
|
|
$key = is_object($item) ? ($item->hasMethod($index) ? $item->$index() : $item->$index) : $item[$index];
|
2011-12-26 09:48:53 +01:00
|
|
|
|
|
|
|
if (array_key_exists($key, $result)) {
|
|
|
|
$result[$key]->push($item);
|
|
|
|
} else {
|
|
|
|
$result[$key] = new ArrayList(array($item));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return $result;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2012-06-23 00:32:43 +02:00
|
|
|
* Similar to {@link groupBy()}, but returns
|
|
|
|
* the data in a format which is suitable for usage in templates.
|
|
|
|
*
|
2011-12-26 09:48:53 +01:00
|
|
|
* @param string $index
|
2012-06-23 00:32:43 +02:00
|
|
|
* @param string $children Name of the control under which children can be iterated on
|
2011-12-26 09:48:53 +01:00
|
|
|
* @return ArrayList
|
|
|
|
*/
|
|
|
|
public function GroupedBy($index, $children = 'Children') {
|
|
|
|
$grouped = $this->groupBy($index);
|
|
|
|
$result = new ArrayList();
|
|
|
|
|
|
|
|
foreach ($grouped as $indVal => $list) {
|
2013-06-16 14:02:03 +02:00
|
|
|
$list = GroupedList::create($list);
|
2011-12-26 09:48:53 +01:00
|
|
|
$result->push(new ArrayData(array(
|
|
|
|
$index => $indVal,
|
|
|
|
$children => $list
|
|
|
|
)));
|
|
|
|
}
|
|
|
|
|
|
|
|
return $result;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|