auditionadmin/app/Services/DoublerService.php

62 lines
1.8 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, string $mode = 'seating')
{
$cacheKey = 'event'.$event->id.'doublers-'.$mode;
return Cache::remember($cacheKey, 60, function () use ($event, $mode) {
return $this->findDoublersForEvent($event, $mode);
});
}
/**
* @throws TabulationException
*/
protected function findDoublersForEvent(Event $event, string $mode): array
{
$this->validateEvent($event);
$entries = $event->entries;
$entries = match ($mode) {
'seating' => $entries->filter(fn ($entry) => $entry->for_seating === 1),
'advancement' => $entries->filter(fn ($entry) => $entry->for_advance === 1),
};
$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');
}
}
}