ShopBuyLimitValidator.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace App\Module\Shop\Validators;
  3. use UCore\Validator;
  4. /**
  5. * 商店购买限制验证器
  6. *
  7. * 验证用户购买数量是否超出限制
  8. */
  9. class ShopBuyLimitValidator extends Validator
  10. {
  11. /**
  12. * 验证购买限制
  13. *
  14. * @param mixed $value 商品ID
  15. * @param array $data 包含用户ID和购买数量的数组
  16. * @return bool 验证是否通过
  17. */
  18. public function validate(mixed $value, array $data): bool
  19. {
  20. // 从 args 获取参数键名
  21. $userIdKey = $this->args[0] ?? 'user_id';
  22. $numberKey = $this->args[1] ?? 'number';
  23. $shopItemKey = $this->args[2] ?? 'shop_item';
  24. $userId = $data[$userIdKey] ?? null;
  25. $number = $data[$numberKey] ?? null;
  26. $shopItem = $this->validation->$shopItemKey ?? null;
  27. if (!$userId || !$number || !$shopItem) {
  28. $this->addError('验证购买限制时缺少必要参数');
  29. return false;
  30. }
  31. try {
  32. // 检查购买限制
  33. if ($shopItem->max_buy > 0) {
  34. // 获取用户已购买数量
  35. $boughtCount = $shopItem->getUserBoughtCount($userId);
  36. if ($boughtCount + $number > $shopItem->max_buy) {
  37. $remainingCount = $shopItem->max_buy - $boughtCount;
  38. $this->addError("超出购买限制,最多还能购买{$remainingCount}个");
  39. return false;
  40. }
  41. }
  42. return true;
  43. } catch (\Exception $e) {
  44. $this->addError('验证购买限制时发生错误: ' . $e->getMessage());
  45. return false;
  46. }
  47. }
  48. }