Skip to content

Commit

Permalink
[ENH] support aggregate callback
Browse files Browse the repository at this point in the history
  • Loading branch information
n3o77 committed Apr 12, 2022
1 parent d0f76b1 commit 6c904f8
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 10 deletions.
16 changes: 9 additions & 7 deletions src/ColumnType/NumberColumn.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 10 additions & 3 deletions src/Service/GridService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 6c904f8

Please sign in to comment.