当前位置: 首页 > news >正文

起名最好的网站排名500个游戏推广群

起名最好的网站排名,500个游戏推广群,网站框架模板,网站后台模版官方文档:Hyperf 验证器报错需要配合多语言使用,创建配置自动生成对应的语言文件。 一 安装 composer require hyperf/validation:v2.2.33 composer require hyperf/translation:v2.2.33php bin/hyperf.php vendor:publish hyperf/translation php bi…

官方文档:Hyperf

验证器报错需要配合多语言使用,创建配置自动生成对应的语言文件。

一 安装

composer require hyperf/validation:v2.2.33
composer require hyperf/translation:v2.2.33php bin/hyperf.php vendor:publish hyperf/translation
php bin/hyperf.php vendor:publish hyperf/validation
# config/autoload/middlewares.php 加中间件
return [// 下面的 http 字符串对应 config/autoload/server.php 内每个 server 的 name 属性对应的值,意味着对应的中间件配置仅应用在该 Server 中'http' => [// 数组内配置您的全局中间件,顺序根据该数组的顺序\Hyperf\Validation\Middleware\ValidationMiddleware::class],
];# /config/autoload/exception.php 加异常处理
return ['handler' => [// 这里对应您当前的 Server 名称'http' => [\Hyperf\Validation\ValidationExceptionHandler::class,],],
];

二 使用

#创建验证器
php bin/hyperf.php gen:request FooRequest
#设置验证规则 App\Request\FooRequest
public function rules(): array
{return ['foo' => 'required|max:255','bar' => 'required',];
}#设置验证规则 App\Controller\TestController
public function test9(FooRequest $request){// 传入的请求通过验证...// 获取通过验证的数据...$validated = $request->validated();var_dump($validated);}

 比如请求http://127.0.0.1:9501/test/test9?foo=300,返回字符串"bar 字段是必须的"。foo规则max是判断字符长度,foo的用于比较的值是3,所以没报错。

三 规则

#用于文件校验
protected $fileRules = ['File', 'Image', 'Mimes', 'Mimetypes', 'Min','Max', 'Size', 'Between', 'Dimensions',
];#固有验证
protected $implicitRules = ['Required', 'Filled', 'RequiredWith', 'RequiredWithAll', 'RequiredWithout','RequiredWithoutAll', 'RequiredIf', 'RequiredUnless', 'Accepted', 'Present',
];
#依赖验证
protected $dependentRules = ['RequiredWith', 'RequiredWithAll', 'RequiredWithout', 'RequiredWithoutAll','RequiredIf', 'RequiredUnless', 'Confirmed', 'Same', 'Different', 'Unique','Before', 'After', 'BeforeOrEqual', 'AfterOrEqual', 'Gt', 'Lt', 'Gte', 'Lte',
];#size验证
protected $sizeRules = ['Size', 'Between', 'Min', 'Max', 'Gt', 'Lt', 'Gte', 'Lte'];#数字验证
protected $numericRules = ['Numeric', 'Integer'];

 具体验证使用,查看官方教程。

四 自定义

1、自定义错误信息

#App\Request\FooRequest
public function messages(): array
{return ['foo.required' => 'foo is required','bar.required'  => 'bar is required',];
}

2、自定义属性

#App\Request\FooRequest
public function attributes(): array
{return ['foo' => 'foo of request',];
}

3、自定义验证器

#App\Controller\TestTestController
public function test10(){$validator = $this->validationFactory->make($this->request->all(),['foo' => 'lt:10','bar' => 'required',],['foo.required' => 'foo is required','bar.required' => 'bar is required','lt' => ['numeric' => ':attribute 必须小于 [ :value ]'],'required' => ':attribute 字段是必须的~',]);if ($validator->fails()) {// Handle exception$errorMessage = $validator->errors()->all();var_dump($errorMessage);}var_dump("success");// Do something}#请求
http://127.0.0.1:9501/test/test10?foo=300#输出
array(2) {[0]=>string(27) "测试1 必须小于 [ 10 ]"[1]=>string(15) "bar is required"
}
string(7) "success"

 测试证明 make第三个参数传入对应规则的报错信息,可以将原报错信息覆盖,但是和设置的对应属性的的对应规则的报错信息不兼容。

#修改自定义信息如下 
[    'required' => ':attribute 字段是必须的~','foo.required' => 'foo is required','bar.required' => 'bar is required','lt' => ['numeric' => ':attribute 必须小于 [ :value ]'],'required' => ':attribute 字段是必须的~',]#请求内容不变 报错信息
array(2) {[0]=>string(27) "测试1 必须小于 [ 10 ]"[1]=>string(15) "bar is required"
}
string(7) "success"

 定义了属性的具体的报错信息,则采用属性的对应规则的报错信息。

4、自定义属性名

根据上述代码,在语言设置中如属性名。

#\storage\languages\zh_CN\validation.php
'attributes' => ['foo' => '测试1','bar' => '测试2',],#请求 
http://127.0.0.1:9501/test/test10?foo=300#输出
array(2) {[0]=>string(23) "测试1 必须小于 10"[1]=>string(15) "bar is required"
}
string(7) "success"

 根据测试证明 自定义中多语言字符串的设置,和其自带的不共用,需自己设置。

五 错误处理

错误返回信息使用类Hyperf\Utils\MessageBag。

MessageBag::add()  增加报错信息

MessageBag::has() 判断是否有某个属性报错

MessageBag::hasAny() 判断是否有某个属性报错

MessageBag::isEmpty() 判断是否为空

MessageBag::isNotEmpty() 、MessageBag::any() 判断是否不为空

MessageBag::first() 获取第一个报错

MessageBag::get() 获取某个属性的报错

MessageBag::all() 获取全部报错

MessageBag::unique();

MessageBag::messages()、MessageBag::getMessages()、MessageBag::toArray()、MessageBag::jsonSerialize() 返回错误信息数组,键值为属性名

还有些其他的,可以去看源码,使用方法可以看官方文档。

实际上$validator->errors()返回对象就是这个类。

六 详解

从使用 php bin/hyperf.php gen:request说起。

生成 Hyperf\Validation\Request\FormRequest\FormRequest子类,可以重写messages自定义消息、重写attributes自定义属性,必须设置rules方法定义验证规则,使用validated方法验证。使用验证返回的对象处理错误信息。其中错误信息以来于多语言模块。

验证流程:

FormRequest::validated()->FormRequest::getValidatorInstance()->FormRequest::createDefaultValidator()->Validator::validated()->Validator::invalid()->Validator::passes()->Validator::validateAttribute()->ValidatesAttributes::属性验证->FormatsMessages::makeReplacements()-> MessageBag::add(),最后返回可用的请求数据。

FormRequest::createDefaultValidator()获取默认验证器,传入通过容器获取的ValidatorFactory实体类,调用ValidatorFactory::make()->ValidatorFactory::resolve()流程,创建Validator对象并返回。

ValidatesAttributes类和FormatsMessages类都是trait类,通过在Validator类中使用use加载到类中。

源码如下

#模块配置内容 Hyperf\Validation\ConfigProvider'dependencies' => [PresenceVerifierInterface::class => DatabasePresenceVerifierFactory::class,FactoryInterface::class => ValidatorFactoryFactory::class,],
#Hyperf\Validation\Request\FormRequest
class FormRequest extends Request implements ValidatesWhenResolved
{public function validated(): array{return $this->getValidatorInstance()->validated();}public function messages(): array{return [];}public function attributes(): array{return [];}protected function getValidatorInstance(): ValidatorInterface{……if (method_exists($this, 'validator')) {$validator = call_user_func_array([$this, 'validator'], compact('factory'));} else {$validator = $this->createDefaultValidator($factory);}if (method_exists($this, 'withValidator')) {$this->withValidator($validator);}return $validator;});}protected function createDefaultValidator(ValidationFactory $factory): ValidatorInterface{return $factory->make($this->validationData(),$this->getRules(),$this->messages(),$this->attributes());}protected function getRules(){$rules = call_user_func_array([$this, 'rules'], []);$scene = $this->getScene();if ($scene && isset($this->scenes[$scene]) && is_array($this->scenes[$scene])) {$newRules = [];foreach ($this->scenes[$scene] as $field) {if (array_key_exists($field, $rules)) {$newRules[$field] = $rules[$field];}}return $newRules;}return $rules;}
}
#Hyperf\Validatio\ValidatorFactory
public function make(array $data, array $rules, array $messages = [], array     $customAttributes = []): ValidatorInterface{$validator = $this->resolve($data,$rules,$messages,$customAttributes);……return $validator;}
protected function resolve(array $data, array $rules, array $messages, array $customAttributes): ValidatorInterface{if (is_null($this->resolver)) {return new Validator($this->translator, $data, $rules, $messages, $customAttributes);}return call_user_func($this->resolver, $this->translator, $data, $rules, $messages, $customAttributes);}
#Hyperf\Validation\Validator
class Validator implements ValidatorContract
{use Concerns\FormatsMessages;use Concerns\ValidatesAttributes;public function after($callback): self{$this->after[] = function () use ($callback) {return call_user_func_array($callback, [$this]);};return $this;}public function validated(): array{if ($this->invalid()) {throw new ValidationException($this);}$results = [];$missingValue = Str::random(10);foreach (array_keys($this->getRules()) as $key) {$value = data_get($this->getData(), $key, $missingValue);if ($value !== $missingValue) {Arr::set($results, $key, $value);}}return $results;}public function invalid(): array{if (!$this->messages) {$this->passes();}return array_intersect_key($this->data,$this->attributesThatHaveMessages());}public function passes(): bool{$this->messages = new MessageBag();[$this->distinctValues, $this->failedRules] = [[], []];// We'll spin through each rule, validating the attributes attached to that// rule. Any error messages will be added to the containers with each of// the other error messages, returning true if we don't have messages.foreach ($this->rules as $attribute => $rules) {$attribute = str_replace('\.', '->', $attribute);foreach ($rules as $rule) {$this->validateAttribute($attribute, $rule);if ($this->shouldStopValidating($attribute)) {break;}}}// Here we will spin through all of the "after" hooks on this validator and// fire them off. This gives the callbacks a chance to perform all kinds// of other validation that needs to get wrapped up in this operation.foreach ($this->after as $after) {call_user_func($after);}return $this->messages->isEmpty();}protected function validateAttribute(string $attribute, $rule){……$method = "validate{$rule}";if ($validatable && !$this->{$method}($attribute, $value, $parameters, $this)) {$this->addFailure($attribute, $rule, $parameters);}}
}#假如判断lt
$method = "validateLt";#Hyperf\Validation\Concerns\ValidatesAttributespublic function validateLt(string $attribute, $value, array $parameters): bool{$this->requireParameterCount(1, $parameters, 'lt');$comparedToValue = $this->getValue($parameters[0]);$this->shouldBeNumeric($attribute, 'Lt');if (is_null($comparedToValue) && (is_numeric($value) && is_numeric($parameters[0]))) {return $this->getSize($attribute, $value) < $parameters[0];}if (!$this->isSameType($value, $comparedToValue)) {return false;}return $this->getSize($attribute, $value) < $this->getSize($attribute, $comparedToValue);}
#Hyperf\Utils\MessageBag
class MessageBag implements Arrayable, Countable, Jsonable, JsonSerializable, MessageBagContract, MessageProvider
{public function __construct(array $messages = []){foreach ($messages as $key => $value) {$value = $value instanceof Arrayable ? $value->toArray() : (array) $value;$this->messages[$key] = array_unique($value);}}
}#其余比较多 可以查看源码

http://www.bjxfkj.com.cn/article/103795.html

相关文章:

  • 做的比较好的设计公司网站最近有哪些新闻
  • 竹子网站建站百度下载免费官方安装
  • 网站问题图片百度百度地图
  • 网页设计实验报告总结100字seo优化大公司排名
  • 做网站干什么用武汉网站seo服务
  • 动易建网站广州网站优化外包
  • app网站建设开发nba赛季排名
  • 合肥网站建设方案书seo网站推广批发
  • 哪个网站专门做高清壁纸广州网站建设正规公司
  • 专做批发的网站电子seo网站优化工具大全
  • 建立自己的影视网站抖音优化公司
  • wordpress 网站静态模板网站
  • 门户网站开发需求怎样注册自己的网站
  • 网站建设业绩其他搜索引擎
  • 做爰全过程的视频的网站北京刚刚宣布比疫情更可怕的事情
  • 分销商城解决方案西安seo关键字优化
  • 网站没服务器行吗软文写作500字
  • 网站建设报价明细表创网站永久免费建站
  • 网站建设网络拓扑百度2023免费下载
  • asp.net 做网站文章是怎么存储的自己做seo网站推广
  • 紫色风格网站关键词优化
  • 关于网站建设申请百度推广的几种方式
  • 自己做的视频可以传别的网站去吗凡科网微信小程序
  • 网站开发女生适合吗购买链接怎么买
  • 做搞基视频网站合肥seo服务商
  • 郑州做营销型网站公司厦门seo搜索引擎优化
  • 怎么制作移动端网站品牌推广营销
  • 安徽网站建设公司排名苏州首页排名关键词优化
  • 网站代码怎么改网站开发语言
  • wordpress 多个主题网站快速排名优化