Skip to content

Commit

Permalink
fix: turnout repository (#81)
Browse files Browse the repository at this point in the history
  • Loading branch information
andreiio authored Nov 24, 2024
1 parent 6ab4eeb commit 3b694d1
Showing 1 changed file with 12 additions and 19 deletions.
31 changes: 12 additions & 19 deletions app/Repositories/TurnoutRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -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,
Expand All @@ -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(
Expand Down Expand Up @@ -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,
Expand All @@ -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();
});
}
}

0 comments on commit 3b694d1

Please sign in to comment.