PhoneCodeValidator.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace App\Module\Sms\Validators;
  3. use App\Module\Sms\Services\SmsService;
  4. use UCore\Exception\LogicException;
  5. use UCore\Validator;
  6. /**
  7. * 手机验证码验证器
  8. */
  9. class PhoneCodeValidator extends Validator
  10. {
  11. /**
  12. * 验证规则
  13. *
  14. * @return array
  15. */
  16. public function rules(): array
  17. {
  18. return [
  19. 'type' => 'required|string',
  20. 'phone' => 'required|string',
  21. 'code' => 'required|string|size:6',
  22. ];
  23. }
  24. /**
  25. * 错误消息
  26. *
  27. * @return array
  28. */
  29. public function messages(): array
  30. {
  31. return [
  32. 'type.required' => '验证码类型不能为空',
  33. 'type.string' => '验证码类型必须是字符串',
  34. 'phone.required' => '手机号不能为空',
  35. 'phone.string' => '手机号必须是字符串',
  36. 'code.required' => '验证码不能为空',
  37. 'code.string' => '验证码必须是字符串',
  38. 'code.size' => '验证码必须是6位数字',
  39. ];
  40. }
  41. public function validate(mixed $value, array $data): bool
  42. {
  43. return true;
  44. return self::validateCode($data['type'], $data['phone'], $data['code']);
  45. }
  46. /**
  47. * 验证手机验证码
  48. *
  49. * @param string $type 验证码类型
  50. * @param string $phone 手机号
  51. * @param string $code 验证码
  52. * @return bool
  53. * @throws LogicException
  54. */
  55. public function validateCode(string $type, string $phone, string $code): bool
  56. {
  57. if (empty($type) || empty($phone) || empty($code)) {
  58. throw new LogicException('参数错误');
  59. }
  60. $smsService = app(SmsService::class);
  61. return $smsService->verifyCode($type, $phone, $code);
  62. }
  63. }