TYPO3 CMS  TYPO3_6-2
GroupedForViewHelper.php
Go to the documentation of this file.
1 <?php
3 
4 /* *
5  * This script is backported from the TYPO3 Flow package "TYPO3.Fluid". *
6  * *
7  * It is free software; you can redistribute it and/or modify it under *
8  * the terms of the GNU Lesser General Public License, either version 3 *
9  * of the License, or (at your option) any later version. *
10  * *
11  * The TYPO3 project - inspiring people to share! *
12  * */
13 
73 
85  public function render($each, $as, $groupBy, $groupKey = 'groupKey') {
86  $output = '';
87  if ($each === NULL) {
88  return '';
89  }
90  if (is_object($each)) {
91  if (!$each instanceof \Traversable) {
92  throw new \TYPO3\CMS\Fluid\Core\ViewHelper\Exception('GroupedForViewHelper only supports arrays and objects implementing \Traversable interface', 1253108907);
93  }
94  $each = iterator_to_array($each);
95  }
96 
97  $groups = $this->groupElements($each, $groupBy);
98 
99  foreach ($groups['values'] as $currentGroupIndex => $group) {
100  $this->templateVariableContainer->add($groupKey, $groups['keys'][$currentGroupIndex]);
101  $this->templateVariableContainer->add($as, $group);
102  $output .= $this->renderChildren();
103  $this->templateVariableContainer->remove($groupKey);
104  $this->templateVariableContainer->remove($as);
105  }
106  return $output;
107  }
108 
117  protected function groupElements(array $elements, $groupBy) {
118  $groups = array('keys' => array(), 'values' => array());
119  foreach ($elements as $key => $value) {
120  if (is_array($value)) {
121  $currentGroupIndex = isset($value[$groupBy]) ? $value[$groupBy] : NULL;
122  } elseif (is_object($value)) {
123  $currentGroupIndex = \TYPO3\CMS\Extbase\Reflection\ObjectAccess::getPropertyPath($value, $groupBy);
124  } else {
125  throw new \TYPO3\CMS\Fluid\Core\ViewHelper\Exception('GroupedForViewHelper only supports multi-dimensional arrays and objects', 1253120365);
126  }
127  $currentGroupKeyValue = $currentGroupIndex;
128  if (is_object($currentGroupIndex)) {
129  if ($currentGroupIndex instanceof \TYPO3\CMS\Extbase\Persistence\Generic\LazyLoadingProxy) {
130  $currentGroupIndex = $currentGroupIndex->_loadRealInstance();
131  }
132  $currentGroupIndex = spl_object_hash($currentGroupIndex);
133  }
134  $groups['keys'][$currentGroupIndex] = $currentGroupKeyValue;
135  $groups['values'][$currentGroupIndex][$key] = $value;
136  }
137  return $groups;
138  }
139 }
static getPropertyPath($subject, $propertyPath)
render($each, $as, $groupBy, $groupKey='groupKey')