| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- <?php
- /**
- * 参数校验服务
- */
- namespace services\common;
- use common\components\Service;
- use common\models\common\ParamsValidateModel;
- /**
- *
- * Class ParamsValidateService
- * @package services\common
- */
- class ParamsValidateService extends Service
- {
- /**
- * @var ParamsValidateModel 模型
- */
- private $model = null;
- public function init()
- {
- parent::init();
- }
- /**
- * @param array $data 数据项
- * @param array $rules 验证规则
- * @return bool
- */
- public function validate(&$data, $rules,$attributeLabels=[])
- {
- $this->model = new ParamsValidateModel();
- // 添加验证规则
- $this->model->setRules($rules);
- $this->model->setAttributeLabels($attributeLabels);
- //所有参数进行 trim处理
- if(is_array($data)){
- foreach($data as $key => $val){
- $data[$key] = is_string($val) ? trim($val) : $val;
- }
- }
- // 设置参数
- $this->model->load($data, '');
- // 进行验证
- $valid = $this->model->validate();
- // 覆盖值,使 default 验证器生效。
- $data = $this->model->attributes;
- return $valid;
- }
- /**
- * 获取第一条验证错误消息内容
- * @return mixed
- */
- public function getFirstErrorSummary()
- {
- $errors = $this->model->getErrorSummary(false);
- return current($errors);
- }
- /**
- * 获取模型错误
- * @Author bing
- * @DateTime 2020-10-27 15:27:47
- * @copyright: Copyright (c) 2020 广东七件事集团
- * @param [type] $model
- * @return void|mixed
- */
- public function getErrorMessage($model = null){
-
- $first_error = $this->getFirstErrorSummary();
- return $first_error;
- }
- public function __call($name, $params)
- {
- if ($this->model->hasMethod($name)) {
- return call_user_func_array([$this->model, $name], $params);
- } else {
- return parent::__call($name, $params);
- }
- }
- }
|