From afc8367e5670eda6b699e8fd5790bef764e25245 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=2E=20Nagy=20Gerg=C5=91?= Date: Sat, 23 Dec 2023 12:20:40 +0100 Subject: [PATCH] refactor --- src/Widgets/Value.php | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/src/Widgets/Value.php b/src/Widgets/Value.php index ef768ead..508da030 100644 --- a/src/Widgets/Value.php +++ b/src/Widgets/Value.php @@ -76,50 +76,60 @@ public function resolveQuery(Request $request): Builder /** * Aggregate count values. */ - public function count(Request $request, Builder $query, string $column = '*'): ValueResult + protected function count(Request $request, Builder $query, string $column = '*'): ValueResult { return $this->toResult( - $query->selectRaw(sprintf('count(%s) as `__value`', $query->getQuery()->getGrammar()->wrap($column))) + $this->aggregate($query, 'count', $column) ); } /** * Aggregate average values. */ - public function avg(Request $request, Builder $query, string $column): ValueResult + protected function avg(Request $request, Builder $query, string $column): ValueResult { return $this->toResult( - $query->selectRaw(sprintf('avg(%s) as `__value`', $query->getQuery()->getGrammar()->wrap($column))) + $this->aggregate($query, 'avg', $column) ); } /** * Aggregate min values. */ - public function min(Request $request, Builder $query, string $column): ValueResult + protected function min(Request $request, Builder $query, string $column): ValueResult { return $this->toResult( - $query->selectRaw(sprintf('min(%s) as `__value`', $query->getQuery()->getGrammar()->wrap($column))) + $this->aggregate($query, 'min', $column) ); } /** * Aggregate max values. */ - public function max(Request $request, Builder $query, string $column): ValueResult + protected function max(Request $request, Builder $query, string $column): ValueResult { return $this->toResult( - $query->selectRaw(sprintf('max(%s) as `__value`', $query->getQuery()->getGrammar()->wrap($column))) + $this->aggregate($query, 'max', $column) ); } /** * Aggregate sum values. */ - public function sum(Request $request, Builder $query, string $column): ValueResult + protected function sum(Request $request, Builder $query, string $column): ValueResult { return $this->toResult( - $query->selectRaw(sprintf('sum(%s) as `__value`', $query->getQuery()->getGrammar()->wrap($column))) + $this->aggregate($query, 'sum', $column) + ); + } + + /** + * Apply the aggregate function on the query. + */ + protected function aggregate(Builder $query, string $fn, string $column): Builder + { + return $query->selectRaw( + sprintf('%s(%s) as `__value`', $fn, $query->getQuery()->getGrammar()->wrap($column)) ); }