createEntry($student, $audition, $entry_for); } public function createEntry(Student $student, Audition $audition, string|array|null $entry_for = null) { if (! $entry_for) { $entry_for = ['seating', 'advancement']; } $entry_for = collect($entry_for); $this->verifySubmission($student, $audition); $entry = Entry::make([ 'student_id' => $student->id, 'audition_id' => $audition->id, 'draw_number' => $this->checkDraw($audition), 'for_seating' => $entry_for->contains('seating'), 'for_advancement' => $entry_for->contains('advancement'), ]); $entry->save(); return $entry; } private function checkDraw(Audition $audition) { if (! $audition->hasFlag('drawn')) { return null; } // get the maximum value of draw_number from $audition->entries() $draw_number = $audition->entries()->max('draw_number'); return $draw_number + 1; } private function verifySubmission(Student $student, Audition $audition): void { // Make sure it's a valid student if (! $student->exists()) { throw new CreateEntryException('Invalid student provided'); } // Make sure the audition is valid if (! $audition->exists()) { throw new CreateEntryException('Invalid audition provided'); } // A student can't enter the same audition twice if (Entry::where('student_id', $student->id)->where('audition_id', $audition->id)->exists()) { throw new CreateEntryException('That student is already entered in that audition'); } // Can't enter a published audition if ($audition->hasFlag('seats_published')) { throw new CreateEntryException('Cannot add an entry to an audition where seats are published'); } if ($audition->hasFlag('advancement_published')) { throw new CreateEntryException('Cannot add an entry to an audition where advancement is published'); } // Verify the grade of the student is in range for the audition if ($student->grade > $audition->maximum_grade) { throw new CreateEntryException('The grade of the student exceeds the maximum for that audition'); } if ($student->grade < $audition->minimum_grade) { throw new CreateEntryException('The grade of the student does not meet the minimum for that audition'); } } }