ULimitDayTimeValidator.php 1.6 KB

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