auditionadmin/app/Services/DoublerService.php

58 lines
1.5 KiB
PHP

<?php
namespace App\Services;
use App\Exceptions\TabulationException;
use App\Models\Entry;
use App\Models\Event;
use App\Models\Student;
use Illuminate\Support\Facades\Cache;
/**
* returns a collection of doublers for the event in the form of
* [studentId => [student=>student, entries=>[entries]]
*/
class DoublerService
{
public function doublersForEvent(Event $event)
{
$cacheKey = 'event'.$event->id.'doublers';
return Cache::remember($cacheKey, 60, function () use ($event) {
return $this->findDoublersForEvent($event);
});
}
/**
* @throws TabulationException
*/
protected function findDoublersForEvent(Event $event): array
{
$this->validateEvent($event);
$entries = $event->entries;
$entries->load('student.school');
$entries->load('audition');
$grouped = $entries->groupBy('student_id');
// Filter out student groups with only one entry in the event
$grouped = $grouped->filter(fn ($s) => $s->count() > 1);
$doubler_array = [];
foreach ($grouped as $student_id => $entries) {
$doubler_array[$student_id] = [
'student' => $entries[0]->student,
'entries' => $entries,
];
}
return $doubler_array;
}
/**
* @throws TabulationException
*/
protected function validateEvent(Event $event)
{
if (! $event->exists) {
throw new TabulationException('Invalid event provided');
}
}
}