Files
chatroom/app/Http/Requests/StoreRoomRequest.php
T

72 lines
2.0 KiB
PHP

<?php
/**
* 文件功能:新建聊天室请求验证器
*
* @author ChatRoom Laravel
*
* @version 1.0.0
*/
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
/**
* 新建聊天室请求验证器
* 负责限制建房权限并拦截危险的房间名称输入。
*/
class StoreRoomRequest extends FormRequest
{
/**
* 判断当前用户是否具备自建房间权限。
*/
public function authorize(): bool
{
// 只有登录用户,且 user_level 达到特定阈值(例如 >= 10)才可以自己建房
// 具体阈值可以根据运营需求调整,此处暂设 10 为门槛。
return Auth::check() && Auth::user()->user_level >= 10;
}
/**
* 返回建房请求的校验规则。
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:50', 'regex:/^[^<>]+$/u', 'unique:rooms,room_name'],
'description' => ['nullable', 'string', 'max:255'],
];
}
/**
* 在校验前整理房间输入,避免空白与危险字符绕过前端限制。
*/
protected function prepareForValidation(): void
{
$name = $this->input('name');
$description = $this->input('description');
$this->merge([
'name' => is_string($name) ? trim($name) : $name,
'description' => is_string($description) ? trim($description) : $description,
]);
}
/**
* 返回建房失败时的中文提示。
*/
public function messages(): array
{
return [
'name.required' => '必须填写房间名称。',
'name.unique' => '该房间名称已被占用。',
'name.max' => '房间名称最多 50 个字符。',
'name.regex' => '房间名称不能包含尖括号。',
];
}
}