php8.0+ 注解,反射表单验证
创建BaseRequest 继承 FormRequest 并重写createDefaultValidator方法
<?php
namespace App\Requests;
use Illuminate\Contracts\Validation\Factory;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
class BaseRequest extend FormRequest
{
/**
* 验证失败
* @param Validator $validator
* @return mixed
*/protected function failedValidation(Validator $validator): mixed
{
$error = $validator->errors()->all();
throw new HttpResponseException(response()->json(['code' => -1,'message' => $error[0]]));
}
/**
* 表单注解验证 v8.0 +
* @param Factory $factory
* @return Validator
*/
public function createDefaultValidator(Factory $factory): Validator
{
$data = $this->input();
$rules = [];
$class = new \ReflectionClass($this);
$properties = $class->getProperties();
foreach ($properties as $property) {
$attribute = $property->getAttributes()[0] ?? [];
if (empty($attribute)) {
continue;
}
if (! str_ends_with($attribute->getName(), 'Param')) {
continue;
}
// 这是需要注入的表单验证属性
$arguments = $attribute->getArguments();
$key = $arguments['name'];
$rules[$key] = $arguments['rules'];
}
// 合并
$rules = array_merge($this->rules(), $rules);
$messages = array_merge($this->messages(), []);
$attributes = array_merge($this->attributes(), []);
return $factory->make($data, $rules, $messages, $attributes);
}
}
创建自定义注解类
<?php
namespace App\Annotation;
use Attribute;
#[Attribute(Attribute::TARGET_PROPERTY)]
class Param
{
public function __construct(
public string $name,
public array $rules)
{}
}
测试request类
<?php
namespace App\Requests;
use App\Annotation\Param;
class UserRequest extends BaseRequest
{
#[Param(name: 'username', rules: ['required', 'string', 'max:20'])]
protected string $name;
#[Param(name: 'secret', rules: ['required', 'string', 'min:6', 'max:20'])]
protected string $secret;
#[Param(name: 'type', rules: ['required', 'in:1,2,3'])]
protected string $type;
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: