]> git.localhorst.tv Git - alttp.git/blob - app/Http/Controllers/ResultController.php
result comments
[alttp.git] / app / Http / Controllers / ResultController.php
1 <?php
2
3 namespace App\Http\Controllers;
4
5 use App\Events\ResultChanged;
6 use App\Models\Participant;
7 use App\Models\Protocol;
8 use App\Models\Result;
9 use App\Models\Round;
10 use Illuminate\Http\Request;
11
12 class ResultController extends Controller
13 {
14
15         public function create(Request $request) {
16                 $validatedData = $request->validate([
17                         'comment' => 'string',
18                         'forfeit' => 'boolean',
19                         'participant_id' => 'required|exists:App\\Models\\Participant,id',
20                         'round_id' => 'required|exists:App\\Models\\Round,id',
21                         'time' => 'numeric',
22                 ]);
23
24                 $participant = Participant::findOrFail($validatedData['participant_id']);
25                 $round = Round::findOrFail($validatedData['round_id']);
26
27                 $user = $request->user();
28                 if ($user->id != $participant->user->id) {
29                         $this->authorize('create', Result::class);
30                 }
31
32                 $result = Result::firstOrCreate([
33                         'round_id' => $validatedData['round_id'],
34                         'user_id' => $participant->user_id,
35                 ]);
36                 if (!$round->locked) {
37                         if (isset($validatedData['forfeit'])) $result->forfeit = $validatedData['forfeit'];
38                         if (isset($validatedData['time'])) $result->time = $validatedData['time'];
39                 }
40                 $result->comment = $validatedData['comment'] ? $validatedData['comment'] : null;
41                 $result->save();
42
43                 if ($result->wasChanged()) {
44                         ResultChanged::dispatch($result);
45                 }
46
47                 if ($result->wasChanged(['forfeit', 'time'])) {
48                         Protocol::resultReported(
49                                 $round->tournament,
50                                 $result,
51                                 $request->user(),
52                         );
53                 } else if ($result->wasChanged('comment')) {
54                         Protocol::resultCommented(
55                                 $round->tournament,
56                                 $result,
57                                 $request->user(),
58                         );
59                 }
60
61                 $round->load('results');
62                 $round->updatePlacement();
63                 $round->tournament->updatePlacement();
64
65                 return $result->toJson();
66         }
67
68 }