ShopBuyLimitValidator.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. // 使用新的统一限购检查方法
  32. list($canPurchase, $errorMessage, $remainingQuantity) = $shopItem->canUserPurchaseWithLimits($userId, $number);
  33. if (!$canPurchase) {
  34. $this->addError($errorMessage);
  35. return false;
  36. }
  37. return true;
  38. }
  39. }