From 3b694d1aeb6d62dc14591a079a4cd3dbb7513248 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andrei=20Ioni=C8=9B=C4=83?= Date: Sun, 24 Nov 2024 02:26:21 +0200 Subject: [PATCH] fix: turnout repository (#81) --- app/Repositories/TurnoutRepository.php | 31 ++++++++++---------------- 1 file changed, 12 insertions(+), 19 deletions(-) diff --git a/app/Repositories/TurnoutRepository.php b/app/Repositories/TurnoutRepository.php index e2758c1..77dc9dc 100644 --- a/app/Repositories/TurnoutRepository.php +++ b/app/Repositories/TurnoutRepository.php @@ -9,7 +9,6 @@ use App\Models\Turnout; use App\Services\CacheService; use Illuminate\Database\Eloquent\Builder as EloquentBuilder; -use Illuminate\Database\Query\Builder as QueryBuilder; class TurnoutRepository { @@ -29,8 +28,8 @@ public static function getForLevel( array $addSelect = [], ) { return CacheService::make('turnout', $election, $level, $country, $county, $locality, $aggregate, $toBase, $addSelect) - ->remember( - fn () => Turnout::query() + ->remember(function () use ($election, $level, $country, $county, $locality, $aggregate, $toBase, $addSelect) { + $query = Turnout::query() ->whereBelongsTo($election) ->forLevel( level: $level, @@ -40,13 +39,10 @@ public static function getForLevel( aggregate: $aggregate, ) ->when($addSelect, fn (EloquentBuilder $query) => $query->addSelect($addSelect)) - ->when($toBase, fn (EloquentBuilder $query) => $query->toBase()) - ->when( - $aggregate, - fn (EloquentBuilder|QueryBuilder $query) => $query->first(), - fn (EloquentBuilder|QueryBuilder $query) => $query->get() - ) - ); + ->when($toBase, fn (EloquentBuilder $query) => $query->toBase()); + + return $aggregate ? $query->first() : $query->get(); + }); } public static function getForLevelAndArea( @@ -87,8 +83,8 @@ public static function getDemographicsForLevel( array $addSelect = [], ) { return CacheService::make(['turnout', 'demographics'], $election, $level, $country, $county, $locality, $aggregate, $toBase, $addSelect) - ->remember( - fn () => Turnout::query() + ->remember(function () use ($election, $level, $country, $county, $locality, $aggregate, $toBase, $addSelect) { + $query = Turnout::query() ->whereBelongsTo($election) ->groupByDemographics( level: $level, @@ -98,12 +94,9 @@ public static function getDemographicsForLevel( aggregate: $aggregate, ) ->when($addSelect, fn (EloquentBuilder $query) => $query->addSelect($addSelect)) - ->when($toBase, fn (EloquentBuilder $query) => $query->toBase()) - ->when( - $aggregate, - fn (EloquentBuilder|QueryBuilder $query) => $query->first(), - fn (EloquentBuilder|QueryBuilder $query) => $query->get() - ) - ); + ->when($toBase, fn (EloquentBuilder $query) => $query->toBase()); + + return $aggregate ? $query->first() : $query->get(); + }); } }