auditionadmin/app/Actions/Tabulation/EnterBonusScore.php

65 lines
2.1 KiB
PHP

<?php
/** @noinspection PhpUnhandledExceptionInspection */
namespace App\Actions\Tabulation;
use App\Exceptions\AuditionAdminException;
use App\Models\BonusScore;
use App\Models\Entry;
use App\Models\User;
use Illuminate\Support\Facades\App;
class EnterBonusScore
{
public function __invoke(User $judge, Entry $entry, int $score): void
{
$getRelatedEntries = App::make(GetBonusScoreRelatedEntries::class);
$this->basicValidations($judge, $entry);
$this->validateJudgeValidity($judge, $entry, $score);
$entries = $getRelatedEntries($entry);
// Create the score for each related entry
foreach ($entries as $relatedEntry) {
// Also delete any cached scores
BonusScore::create([
'entry_id' => $relatedEntry->id,
'user_id' => $judge->id,
'originally_scored_entry' => $entry->id,
'score' => $score,
]);
}
}
protected function basicValidations(User $judge, Entry $entry): void
{
if (! $judge->exists) {
throw new AuditionAdminException('Invalid judge provided');
}
if (! $entry->exists) {
throw new AuditionAdminException('Invalid entry provided');
}
if ($entry->audition->bonusScore->count() === 0) {
throw new AuditionAdminException('Entry does not have a bonus score');
}
}
protected function validateJudgeValidity(User $judge, Entry $entry, $score): void
{
if (BonusScore::where('entry_id', $entry->id)->where('user_id', $judge->id)->exists()) {
throw new AuditionAdminException('That judge has already scored that entry');
}
$bonusScore = $entry->audition->bonusScore->first();
if (! $bonusScore->judges->contains($judge)) {
throw new AuditionAdminException('That judge is not assigned to judge that bonus score');
}
if ($score > $bonusScore->max_score) {
throw new AuditionAdminException('That score exceeds the maximum');
}
}
}