mapolun/easyswoole-normal-validate

This is a validate using TP5 in conjunction with the easyswoole specification

v1.0.5 2019-08-18 18:56 UTC

This package is auto-updated.

Last update: 2024-04-19 05:07:57 UTC


README

This is a validate using TP5 in conjunction with EasyS specification

运行easyswoole的validate结合tp5的验证规则,可自定义func。 验证的规则使用可以参考easyswoole官方的validate,https://www.easyswoole.com/Cn/Components/validate.html

Installation

The recommended method of installing this library is via Composer.

Run the following command from your project root:

$ composer require mapolun/easyswoole-normal-validate

Requirements

  • EasySwoole
  • PHP >= 7.2

Usage

使用规则借鉴tp5规则语法,EasySwoole验证调用方法,验证字段规则值时用~ 符号隔开,可拓展func类型标识自定义函数进行验证规则。

一、创建validate规则

namespace App\Validate;

use MaPoLun\Validate;

/**
 * 登录验证类
 * Class SignIn
 * @package App\Validate\User
 */
class SignIn extends Validate
{
    protected $rule = [
        'username' => 'required|notEmpty',
        'password' => 'required|notEmpty|betweenLen:8~11',
    ];

    protected $message = [
        'username.required' => "缺少必要参数username",
        'username.notEmpty' => "username不可为空",
        'password.required' => "缺少必要参数password",
        'password.notEmpty' => "password不可为空",
        'password.betweenLen' => "password不合法"
    ];
}


二、创建控制器类

namespace App\HttpController;

use App\Validate\SignIn;

class Index extends Base
{
    public function index()
    {
        // TODO: Implement index() method.
        $validate = (new SignIn())->getExamplie();
        $params = $this->validateCheck($validate);
        var_dump($params); // 这是你客户端请求过来验证好的参数
    }
}

三、创建Basenamespace App\HttpController;

use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\Http\Message\Status;
use EasySwoole\Validate\Validate;
use Swoole\Coroutine\Http\Client\Exception;

class Base extends Controller
{
    public function index()
    {
        // TODO: Implement index() method.
    }

    public final function validateCheck($validate) : array
    {
        if ($validate instanceof Validate) {
            if ($this->validate($validate)) {
                return $validate->getVerifiedData();
            } else {
                throw new Exception($validate->getError()->__toString(),Status::CODE_ACCEPTED);
            }
        } else {
            throw new Exception("不属于规则合法验证实例",Status::CODE_INTERNAL_SERVER_ERROR);
        }
    }

    protected function onException(\Throwable $throwable): void
    {
        // TODO: Change the autogenerated stub
        $this->writeJson($throwable->getCode(),'fail',$throwable->getMessage());
        return;
    }
}

Last

喜欢的给我打星星哦,感谢!!!