ValidatorExtension.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /**
  3. * 校验扩展.
  4. */
  5. namespace App\Extensions;
  6. use App\Constants\PatternConstant;
  7. use Illuminate\Support\Str;
  8. class ValidatorExtension
  9. {
  10. private $parameters = [];
  11. private $messages = [];
  12. /**
  13. * 手机号格式校验
  14. * @param string $arruibute 属性
  15. * @param string $value 值
  16. * @param mixed $paramters 参数
  17. * @param null $validator 验证类
  18. * @return bool
  19. */
  20. public function mobile($arruibute, $value, $paramters, $validator = null)
  21. {
  22. $this->setParameters(__FUNCTION__, $paramters);
  23. $this->setMessage(__FUNCTION__);
  24. return (bool)preg_match(PatternConstant::CHINA_MOBILE, $value);
  25. }
  26. /**
  27. * 设置错误消息
  28. * @param string $method 方法名
  29. */
  30. public function setMessage($method)
  31. {
  32. $name = Str::snake($method);
  33. $message = trans('validation.'. $name, $this->getParameters($method));
  34. $this->messages[$name] = !empty($message) ? $message : '';
  35. }
  36. /**
  37. * 获取错误消息
  38. * @param string $method 方法名
  39. * @return mixed|null
  40. */
  41. public function getMessage($method)
  42. {
  43. $name = Str::snake($method);
  44. if (isset($this->messages[$name])) {
  45. return $this->messages[$name];
  46. } else {
  47. $message = trans('validation.'. $name, $this->getParameters($method));
  48. return !empty($message) ? $message : '';
  49. }
  50. }
  51. /**
  52. * 设置参数
  53. * @param string $method 方法名
  54. * @param mixed $paramters 参数
  55. */
  56. public function setParameters($method, $paramters = null)
  57. {
  58. $this->parameters[$method] = $paramters;
  59. }
  60. /**
  61. * 获取参数
  62. * @param string $method 方法名
  63. * @return mixed|null
  64. */
  65. public function getParameters($method)
  66. {
  67. return isset($this->parameters[$method]) ? $this->parameters[$method] : null;
  68. }
  69. }