ChestConsumeValidator.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Module\GameItems\Validators;
  3. use App\Module\GameItems\Models\ItemChestConfig;
  4. use App\Module\Game\Services\ConsumeService;
  5. use UCore\Validator;
  6. /**
  7. * 宝箱消耗验证器
  8. *
  9. * 验证用户是否满足宝箱开启的消耗条件
  10. */
  11. class ChestConsumeValidator extends Validator
  12. {
  13. /**
  14. * 验证宝箱消耗
  15. *
  16. * @param mixed $value 宝箱物品ID
  17. * @param array $data 包含用户ID和数量的数组
  18. * @return bool 验证是否通过
  19. */
  20. public function validate(mixed $value, array $data): bool
  21. {
  22. $chestId = (int)$value;
  23. // 从 args 获取参数键名
  24. $userIdKey = $this->args[0] ?? 'user_id';
  25. $quantityKey = $this->args[1] ?? 'quantity';
  26. $userId = $data[$userIdKey] ?? null;
  27. $quantity = $data[$quantityKey] ?? 1;
  28. if (!$userId) {
  29. $this->addError('用户ID不能为空');
  30. return false;
  31. }
  32. try {
  33. // 获取宝箱配置
  34. $chestConfig = ItemChestConfig::where('item_id', $chestId)
  35. ->where('is_active', true)
  36. ->first();
  37. if (!$chestConfig) {
  38. $this->addError('宝箱配置不存在或未激活');
  39. return false;
  40. }
  41. // 如果没有配置消耗组,则无需验证消耗
  42. if (!$chestConfig->consume_group_id) {
  43. return true;
  44. }
  45. // 检查消耗组条件
  46. $checkResult = ConsumeService::checkConsume($userId, $chestConfig->consume_group_id);
  47. if (!$checkResult->success) {
  48. $this->addError($checkResult->message);
  49. return false;
  50. }
  51. return true;
  52. } catch (\Exception $e) {
  53. $this->addError('验证宝箱消耗时发生错误: ' . $e->getMessage());
  54. return false;
  55. }
  56. }
  57. }