ULimitTimeValidator.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace App\Module\Ulogic\Validator;
  3. use App\Module\Ulogic\Times;
  4. use UCore\Exception\LogicException;
  5. use UCore\Validator;
  6. use UCore\Validator\ConsumeValidator;
  7. /**
  8. * 用户计数限制(数据库,永久计数)
  9. *
  10. */
  11. class ULimitTimeValidator extends Validator implements ConsumeValidator
  12. {
  13. protected $type;
  14. protected $sid;
  15. protected $limit;
  16. protected $user_id;
  17. public function validate(mixed $value, array $data): bool
  18. {
  19. $type = get_class($this->validation);
  20. $this->user_id = $value;
  21. $this->type = $type;
  22. $sid = $this->args['sid'] ?? 0;
  23. $this->sid = $sid;
  24. $limit = $this->args['limit'] ?? 0;
  25. if ($limit <= 0) {
  26. throw new LogicException('Limit is null');
  27. }
  28. $res = self::check($value, $this->type, $sid, $this->limit);
  29. if (!$res) {
  30. $this->validation->addError('', "限制 {$this->limit} 次");
  31. }
  32. return $res;
  33. }
  34. /**
  35. * 限流检查
  36. * @param $user_id
  37. * @param $type
  38. * @param $limit
  39. * @return bool
  40. */
  41. public static function check($user_id, $type, $limit, $sid = 0)
  42. {
  43. if (Times::check($user_id, $type, $sid, $limit)) {
  44. return true;
  45. }
  46. return false;
  47. }
  48. public function consume($times = 1)
  49. {
  50. Times::add($this->user_id, $this->type, $this->sid, $times);
  51. }
  52. }