95 lines
2.2 KiB
PHP
95 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Requests;
|
|
|
|
use Illuminate\Foundation\Http\FormRequest;
|
|
use Illuminate\Contracts\Validation\Validator;
|
|
use Illuminate\Http\Exceptions\HttpResponseException;
|
|
|
|
/**
|
|
* 基础请求验证类
|
|
*/
|
|
abstract class BaseRequest extends FormRequest
|
|
{
|
|
/**
|
|
* 验证是否通过
|
|
*/
|
|
public function authorize(): bool
|
|
{
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* 验证失败时的处理
|
|
*/
|
|
protected function failedValidation(Validator $validator)
|
|
{
|
|
$response = response()->json([
|
|
'success' => false,
|
|
'data' => null,
|
|
'msg' => $validator->errors()->first(),
|
|
'message' => $validator->errors()->first(),
|
|
'code' => 400,
|
|
], 400);
|
|
|
|
throw new HttpResponseException($response);
|
|
}
|
|
|
|
/**
|
|
* 获取公共验证规则
|
|
*/
|
|
protected function getCommonRules(): array
|
|
{
|
|
return [
|
|
'page' => 'sometimes|integer|min:1',
|
|
'page_size' => 'sometimes|integer|min:1|max:100',
|
|
];
|
|
}
|
|
|
|
/**
|
|
* 获取公共验证消息
|
|
*/
|
|
protected function getCommonMessages(): array
|
|
{
|
|
return [
|
|
'page.integer' => '页码必须是数字',
|
|
'page.min' => '页码不能小于1',
|
|
'page_size.integer' => '每页数量必须是数字',
|
|
'page_size.min' => '每页数量不能小于1',
|
|
'page_size.max' => '每页数量不能超过100',
|
|
];
|
|
}
|
|
|
|
/**
|
|
* 合并验证规则
|
|
*/
|
|
public function rules(): array
|
|
{
|
|
$commonRules = $this->getCommonRules();
|
|
$specificRules = $this->getSpecificRules();
|
|
|
|
return array_merge($commonRules, $specificRules);
|
|
}
|
|
|
|
/**
|
|
* 合并验证消息
|
|
*/
|
|
public function messages(): array
|
|
{
|
|
$commonMessages = $this->getCommonMessages();
|
|
$specificMessages = $this->getSpecificMessages();
|
|
|
|
return array_merge($commonMessages, $specificMessages);
|
|
}
|
|
|
|
/**
|
|
* 获取特定的验证规则(子类实现)
|
|
*/
|
|
abstract protected function getSpecificRules(): array;
|
|
|
|
/**
|
|
* 获取特定的验证消息(子类实现)
|
|
*/
|
|
abstract protected function getSpecificMessages(): array;
|
|
}
|