Files
scrum-poker-internal/app/Http/Requests/ShowEmbeddedRoomRequest.php
T
2026-09-10 16:33:13 +02:00

122 lines
3.7 KiB
PHP

<?php
namespace App\Http\Requests;
use App\Models\Player;
use App\Models\Room;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
class ShowEmbeddedRoomRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
protected function prepareForValidation(): void
{
$this->merge([
'join_code' => $this->string('join_code')->trim()->upper()->toString(),
'player_name' => $this->string('player_name')->trim()->toString(),
]);
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'join_code' => [
'bail',
'required',
'string',
'size:6',
Rule::exists(Room::class, 'join_code')->whereNull('deleted_at'),
],
'player_name' => ['required', 'string', 'max:50'],
];
}
/** @return array<callable(Validator): void> */
public function after(): array
{
return [
function (Validator $validator): void {
if ($validator->errors()->has('join_code')) {
return;
}
$room = Room::query()
->where('join_code', $this->input('join_code'))
->first();
if ($room?->isClosed()) {
$validator->errors()->add('join_code', 'Dieser Raum ist geschlossen.');
return;
}
if ($room === null) {
return;
}
$sessionPlayerId = $this->session()->get("room_players.{$room->id}");
$existingPlayer = is_numeric($sessionPlayerId)
? $room->players()->find((int) $sessionPlayerId)
: null;
if ($existingPlayer === null && $this->user() !== null) {
$existingPlayer = $room->players()
->where('user_id', $this->user()->id)
->first();
}
$nameIsTaken = Player::query()
->where('room_id', $room->id)
->where('name', $this->input('player_name'))
->when(
$existingPlayer !== null,
fn ($query) => $query->whereKeyNot($existingPlayer->id),
)
->exists();
if ($nameIsTaken) {
$validator->errors()->add(
'player_name',
'Dieser Anzeigename ist in dem Raum bereits vorhanden.',
);
}
},
];
}
public function messages(): array
{
return [
'join_code.exists' => 'Dieser Raumcode existiert nicht.',
'join_code.size' => 'Der Raumcode muss aus sechs Zeichen bestehen.',
'player_name.required' => 'Bitte hinterlege in der Hub-App einen Anzeigenamen.',
];
}
protected function failedValidation(Validator $validator): never
{
throw new HttpResponseException(
Inertia::render('embedded/Error', [
'message' => $validator->errors()->first(),
])->toResponse($this)->setStatusCode(422),
);
}
}