Hyperf 验证 trait

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

trait类:
<?php
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到验证异常

<?php
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 协议》,转载必须注明作者和本文链接
讨论数量: 1

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!