MCPcopy Create free account
hub / github.com/Rello/analytics / aggregate

Method aggregate

lib/Service/TransformationService.php:223–278  ·  view source on GitHub ↗
(array $rows, array $columns, array $dimensions)

Source from the content-addressed store, hash-verified

221 }
222
223 private function aggregate(array $rows, array $columns, array $dimensions): array {
224 $groups = [];
225 foreach ($rows as $row) {
226 $key = json_encode(array_map(static fn (string $ref): mixed => $row[$ref] ?? null, $dimensions), JSON_THROW_ON_ERROR);
227 if (!isset($groups[$key])) {
228 $groups[$key] = ['values' => array_intersect_key($row, array_flip($dimensions)), 'state' => []];
229 }
230 foreach ($columns as $ref => $column) {
231 if ($column['role'] !== 'measure' || $column['aggregation'] === 'none' || !array_key_exists($ref, $row)) {
232 continue;
233 }
234 $value = $row[$ref];
235 if ($value === null || $value === '') {
236 continue;
237 }
238 $state = &$groups[$key]['state'][$ref];
239 $method = $column['aggregation'];
240 if ($method === 'sum' || $method === 'avg') {
241 if (is_numeric($value)) {
242 $state['sum'] = ($state['sum'] ?? 0.0) + (float)$value;
243 $state['numericCount'] = ($state['numericCount'] ?? 0) + 1;
244 } elseif ($method === 'sum') {
245 $state['lastText'] = $value;
246 }
247 } elseif ($method === 'min') {
248 $state['value'] = isset($state['value']) ? min($state['value'], $value) : $value;
249 } elseif ($method === 'max') {
250 $state['value'] = isset($state['value']) ? max($state['value'], $value) : $value;
251 } elseif ($method === 'count_distinct') {
252 $state['distinct'][json_encode($value, JSON_THROW_ON_ERROR)] = true;
253 }
254 $state['count'] = ($state['count'] ?? 0) + 1;
255 unset($state);
256 }
257 }
258 $result = [];
259 foreach ($groups as $group) {
260 $row = $group['values'];
261 foreach ($columns as $ref => $column) {
262 if ($column['role'] !== 'measure' || $column['aggregation'] === 'none') {
263 continue;
264 }
265 $state = $group['state'][$ref] ?? [];
266 $count = $state['count'] ?? 0;
267 $row[$ref] = match ($column['aggregation']) {
268 'avg' => ($state['numericCount'] ?? 0) ? $state['sum'] / $state['numericCount'] : null,
269 'count' => $count,
270 'count_distinct' => count($state['distinct'] ?? []),
271 'min', 'max' => $state['value'] ?? null,
272 default => $state['sum'] ?? $state['lastText'] ?? null,
273 };
274 }
275 $result[] = $row;
276 }
277 return $result;
278 }
279
280 private function compile(string $expression): array {

Callers 1

executeMethod · 0.95

Calls 1

countFunction · 0.50

Tested by

no test coverage detected