php trait instanceof,Hyperf 验证 trait

模仿Laravel的ValidatesRequest写的一个Trait,仅供参考。

trait类:

namespace App\Controller;

use Hyperf\HttpServer\Contract\RequestInterface;

use Hyperf\Validation\Contract\ValidatorFactoryInterface;

use Hyperf\Contract\ValidatorInterface;

use Hyperf\Validation\ValidationException;

trait ValidatesRequests

{

/**

* @param ValidatorInterface|array $validator

* @param RequestInterface|null $request

* @return array

*

* @throws ValidationException

*/

public function validateWith($validator, RequestInterface $request = null)

{

$request = $request ?? request();

if (is_array($validator)) {

$validator = $this->getValidationFactory()->make($request->all(), $validator);

}

return $validator->validate();

}

/**

* @param RequestInterface $request

* @param array $rules

* @param array $messages

* @param array $customAttributes

* @return mixed

*

* @throws ValidationException

*/

public function validate(RequestInterface $request, array $rules,

array $messages = [], array $customAttributes = [])

{

return $this->getValidationFactory()->make(

$request->all(), $rules, $messages, $customAttributes

)->validate();

}

/**

* @param $errorBag

* @param RequestInterface $request

* @param array $rules

* @param array $messages

* @param array $customAttributes

* @return mixed

*

* @throws ValidationException

*/

public function validateWithBag($errorBag, RequestInterface $request, array $rules,

array $messages = [], array $customAttributes = [])

{

try {

return $this->validate($request, $rules, $messages, $customAttributes);

} catch (ValidationException $e) {

$e->errorBag = $errorBag;

throw $e;

}

}

/**

* @return ValidatorFactoryInterface

*/

protected function getValidationFactory()

{

return make(ValidatorFactoryInterface::class);

}

}

用法:

在 AbstractController 中

use ValidatesRequests;

然后就可以在继承AbstractController所有的控制器中这样使用了:

public function index(RequestInterface $request)

{

$this->validate($request, [

'id' => 'required|integer'

], [], [

'id' => 'ID',

]);

}

异常类

定义一个异常类来catch到验证异常

namespace App\Exception;

use Hyperf\HttpMessage\Stream\SwooleStream;

use Hyperf\Validation\ValidationExceptionHandler;

use Psr\Http\Message\ResponseInterface;

use Throwable;

class ValidationException extends ValidationExceptionHandler

{

public function handle(Throwable $throwable, ResponseInterface $response)

{

$this->stopPropagation();

/** @var \Hyperf\Validation\ValidationException $throwable */

$body = json_encode([

'errors' => $throwable->validator->errors()->first()

], JSON_UNESCAPED_UNICODE);

return $response->withHeader('Content-Type', 'application/json')->withStatus($throwable->status)->withBody(new SwooleStream($body));

}

public function isValid(Throwable $throwable): bool

{

return $throwable instanceof \Hyperf\Validation\ValidationException;

}

}

然后在config/autoload/exceptions.php中添加

return [

'handler' => [

'http' => [

App\Exception\Handler\SystemExceptionHandler::class,

App\Exception\ValidationException::class, //该处就是验证异常类 必须放在AppExceptionHandler上

App\Exception\Handler\AppExceptionHandler::class,

],

],

];

本作品采用《CC 协议》,转载必须注明作者和本文链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值