From 6c904f81d5ef72e71e5bed2eca28c0de3e43555d Mon Sep 17 00:00:00 2001 From: Steffen Persch Date: Wed, 13 Apr 2022 00:03:32 +0200 Subject: [PATCH] [ENH] support aggregate callback --- src/ColumnType/NumberColumn.php | 16 +++++++++------- src/Service/GridService.php | 13 ++++++++++--- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/src/ColumnType/NumberColumn.php b/src/ColumnType/NumberColumn.php index d5aab72..8ad4b20 100644 --- a/src/ColumnType/NumberColumn.php +++ b/src/ColumnType/NumberColumn.php @@ -14,18 +14,20 @@ public function configureOptions(OptionsResolver $resolver): void parent::configureOptions($resolver); $resolver->setDefaults([ - 'nullAsZero' => false, - 'attr' => ['class' => 'text-right'], - 'formatOptions' => [], - 'style' => 'decimal', - 'aggregates' => [], - 'show_aggregate' => null, + 'nullAsZero' => false, + 'attr' => ['class' => 'text-right'], + 'formatOptions' => [], + 'style' => 'decimal', + 'aggregates' => [], + 'show_aggregate' => null, + 'aggregate_callback' => null, ]); $resolver->setAllowedTypes('aggregates', ['array']); $resolver->setAllowedTypes('show_aggregate', ['null', 'string']); + $resolver->setAllowedTypes('aggregate_callback', ['null', 'callable']); - $resolver->setAllowedValues('show_aggregate', [null, 'sum', 'avg', 'min', 'max', 'count', 'count_distinct', 'group_concat', 'std']); + $resolver->setAllowedValues('show_aggregate', [null, 'sum', 'avg', 'min', 'max', 'count', 'count_distinct', 'group_concat', 'std', 'callback']); } public function getAggregateAlias(string $aggregate, string $field): string diff --git a/src/Service/GridService.php b/src/Service/GridService.php index 1664fa6..d24f9d6 100644 --- a/src/Service/GridService.php +++ b/src/Service/GridService.php @@ -171,16 +171,23 @@ public function getAggreagates(GridHelper $gridHelper): ?AggregateResultStruct } $aggregates = [...$column->getOption('aggregates')]; - if ($column->getOption('show_aggregate')) { + if ($column->getOption('show_aggregate') && $column->getOption('show_aggregate') !== 'callback') { $aggregates[] = $column->getOption('show_aggregate'); } + if (is_callable($column->getOption('aggregate_callback'))) { + $aggregates[] = $column->getOption('aggregate_callback'); + } if (\count($aggregates) > 0) { $fieldInfo = RelationsHelper::joinRequiredPaths($qb, $entity, $column->getField()); foreach ($aggregates as $aggregate) { - $aggregateAlias = $columnType->getAggregateAlias($aggregate, $column->getField()); - $aggrFn = strtoupper($aggregate).'('.$fieldInfo->alias.') AS '.$aggregateAlias; + if (is_callable($aggregate)) { + $aggrFn = $aggregate($column, $qb); + } else { + $aggregateAlias = $columnType->getAggregateAlias($aggregate, $column->getField()); + $aggrFn = strtoupper($aggregate).'('.$fieldInfo->alias.') AS '.$aggregateAlias; + } if (0 === $aggregateCount++) { $qb->select($aggrFn);