Last active
December 13, 2015 23:59
-
-
Save smichaelsen/4995910 to your computer and use it in GitHub Desktop.
Enhanced GroupedForViewHelper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Extends the Fluid GroupedByViewHelper with two features: | |
* - support to group by a DateTime property | |
* - new attribute "order", to sort the resulting groups | |
*/ | |
class Tx_MyExt_ViewHelpers_GroupedForViewHelper extends Tx_Fluid_ViewHelpers_GroupedForViewHelper { | |
/** | |
* | |
*/ | |
public function initializeArguments() { | |
$this->registerArgument('order', 'string', 'If set, the groups will be ordered ascending "asc" or descending "desc".', FALSE, NULL); | |
parent::initializeArguments(); | |
} | |
/** | |
* * Groups the given array by the specified groupBy property. | |
* | |
* @param array $elements The array / traversable object to be grouped | |
* @param string $groupBy Group by this property | |
* @return array The grouped array in the form array('keys' => array('key1' => [key1value], 'key2' => [key2value], ...), 'values' => array('key1' => array([key1value] => [element1]), ...), ...) | |
* @throws Tx_Fluid_Core_ViewHelper_Exception | |
*/ | |
protected function groupElements(array $elements, $groupBy) { | |
$groups = array('keys' => array(), 'values' => array()); | |
foreach ($elements as $key => $value) { | |
if (is_array($value)) { | |
$currentGroupIndex = isset($value[$groupBy]) ? $value[$groupBy] : NULL; | |
} elseif (is_object($value)) { | |
$currentGroupIndex = Tx_Extbase_Reflection_ObjectAccess::getProperty($value, $groupBy); | |
} else { | |
throw new Tx_Fluid_Core_ViewHelper_Exception('GroupedForViewHelper only supports multi-dimensional arrays and objects', 1253120365); | |
} | |
$currentGroupKeyValue = $currentGroupIndex; | |
if (is_object($currentGroupIndex)) { | |
if (is_a($currentGroupIndex, 'DateTime')) { | |
$currentGroupIndex = $currentGroupIndex->getTimestamp(); | |
} else { | |
$currentGroupIndex = spl_object_hash($currentGroupIndex); | |
} | |
} | |
$groups['keys'][$currentGroupIndex] = $currentGroupKeyValue; | |
$groups['values'][$currentGroupIndex][$key] = $value; | |
} | |
if ($this->arguments['order']) { | |
$order = strtolower($this->arguments['order']); | |
if (!in_array($order, array('asc', 'desc', 'null'))) { | |
throw new Tx_Fluid_Core_ViewHelper_Exception('order attribute of GroupedForViewHelper must either be "asc", "desc" or "null"', 1361369902); | |
} | |
if (in_array($order, array('asc', 'desc'))) { | |
ksort($groups['values']); | |
} | |
if ($order === 'desc') { | |
$groups['values'] = array_reverse($groups['values'], TRUE); | |
} | |
} | |
return $groups; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment