ParamsValidateService.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * 参数校验服务
  4. */
  5. namespace services\common;
  6. use common\components\Service;
  7. use common\models\common\ParamsValidateModel;
  8. /**
  9. *
  10. * Class ParamsValidateService
  11. * @package services\common
  12. */
  13. class ParamsValidateService extends Service
  14. {
  15. /**
  16. * @var ParamsValidateModel 模型
  17. */
  18. private $model = null;
  19. public function init()
  20. {
  21. parent::init();
  22. }
  23. /**
  24. * @param array $data 数据项
  25. * @param array $rules 验证规则
  26. * @return bool
  27. */
  28. public function validate(&$data, $rules,$attributeLabels=[])
  29. {
  30. $this->model = new ParamsValidateModel();
  31. // 添加验证规则
  32. $this->model->setRules($rules);
  33. $this->model->setAttributeLabels($attributeLabels);
  34. //所有参数进行 trim处理
  35. if(is_array($data)){
  36. foreach($data as $key => $val){
  37. $data[$key] = is_string($val) ? trim($val) : $val;
  38. }
  39. }
  40. // 设置参数
  41. $this->model->load($data, '');
  42. // 进行验证
  43. $valid = $this->model->validate();
  44. // 覆盖值,使 default 验证器生效。
  45. $data = $this->model->attributes;
  46. return $valid;
  47. }
  48. /**
  49. * 获取第一条验证错误消息内容
  50. * @return mixed
  51. */
  52. public function getFirstErrorSummary()
  53. {
  54. $errors = $this->model->getErrorSummary(false);
  55. return current($errors);
  56. }
  57. /**
  58. * 获取模型错误
  59. * @Author bing
  60. * @DateTime 2020-10-27 15:27:47
  61. * @copyright: Copyright (c) 2020 广东七件事集团
  62. * @param [type] $model
  63. * @return void|mixed
  64. */
  65. public function getErrorMessage($model = null){
  66. $first_error = $this->getFirstErrorSummary();
  67. return $first_error;
  68. }
  69. public function __call($name, $params)
  70. {
  71. if ($this->model->hasMethod($name)) {
  72. return call_user_func_array([$this->model, $name], $params);
  73. } else {
  74. return parent::__call($name, $params);
  75. }
  76. }
  77. }