TYPO3 CMS  TYPO3_7-6
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  {
87  $output = '';
88  if ($each === null) {
89  return '';
90  }
91  if (is_object($each)) {
92  if (!$each instanceof \Traversable) {
93  throw new \TYPO3\CMS\Fluid\Core\ViewHelper\Exception('GroupedForViewHelper only supports arrays and objects implementing \Traversable interface', 1253108907);
94  }
95  $each = iterator_to_array($each);
96  }
97 
98  $groups = $this->groupElements($each, $groupBy);
99 
100  foreach ($groups['values'] as $currentGroupIndex => $group) {
101  $this->templateVariableContainer->add($groupKey, $groups['keys'][$currentGroupIndex]);
102  $this->templateVariableContainer->add($as, $group);
103  $output .= $this->renderChildren();
104  $this->templateVariableContainer->remove($groupKey);
105  $this->templateVariableContainer->remove($as);
106  }
107  return $output;
108  }
109 
118  protected function groupElements(array $elements, $groupBy)
119  {
120  $groups = ['keys' => [], 'values' => []];
121  foreach ($elements as $key => $value) {
122  if (is_array($value)) {
123  $currentGroupIndex = isset($value[$groupBy]) ? $value[$groupBy] : null;
124  } elseif (is_object($value)) {
125  $currentGroupIndex = \TYPO3\CMS\Extbase\Reflection\ObjectAccess::getPropertyPath($value, $groupBy);
126  } else {
127  throw new \TYPO3\CMS\Fluid\Core\ViewHelper\Exception('GroupedForViewHelper only supports multi-dimensional arrays and objects', 1253120365);
128  }
129  $currentGroupKeyValue = $currentGroupIndex;
130  if (is_object($currentGroupIndex)) {
131  if ($currentGroupIndex instanceof \TYPO3\CMS\Extbase\Persistence\Generic\LazyLoadingProxy) {
132  $currentGroupIndex = $currentGroupIndex->_loadRealInstance();
133  }
134  $currentGroupIndex = spl_object_hash($currentGroupIndex);
135  }
136  $groups['keys'][$currentGroupIndex] = $currentGroupKeyValue;
137  $groups['values'][$currentGroupIndex][$key] = $value;
138  }
139  return $groups;
140  }
141 }
static getPropertyPath($subject, $propertyPath)
render($each, $as, $groupBy, $groupKey='groupKey')