ShopFundValidator.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace App\Module\Shop\Validators;
  3. use App\Module\Game\Services\ConsumeService;
  4. use UCore\Validator;
  5. /**
  6. * 商店资金验证器
  7. *
  8. * 验证用户资金是否充足
  9. */
  10. class ShopFundValidator extends Validator
  11. {
  12. /**
  13. * 验证用户资金
  14. *
  15. * @param mixed $value 商品ID
  16. * @param array $data 包含用户ID和购买数量的数组
  17. * @return bool 验证是否通过
  18. */
  19. public function validate(mixed $value, array $data): bool
  20. {
  21. // 从 args 获取参数键名
  22. $userIdKey = $this->args[0] ?? 'user_id';
  23. $numberKey = $this->args[1] ?? 'number';
  24. $shopItemKey = $this->args[2] ?? 'shop_item';
  25. $userId = $data[$userIdKey] ?? null;
  26. $number = $data[$numberKey] ?? null;
  27. $shopItem = $this->validation->$shopItemKey ?? null;
  28. if (!$userId || !$number || !$shopItem) {
  29. $this->addError('验证资金时缺少必要参数');
  30. return false;
  31. }
  32. try {
  33. // 检查商品是否有消耗组
  34. if ($shopItem->consume_group_id) {
  35. // 循环检查每个购买数量的消耗条件
  36. for ($i = 0; $i < $number; $i++) {
  37. $consumeValidation = ConsumeService::checkConsume($userId, $shopItem->consume_group_id);
  38. if (!$consumeValidation->success) {
  39. $this->addError($consumeValidation->message);
  40. return false;
  41. }
  42. }
  43. }
  44. return true;
  45. } catch (\Exception $e) {
  46. $this->addError('验证消耗条件时发生错误: ' . $e->getMessage());
  47. return false;
  48. }
  49. }
  50. }