ChestOpenCostValidator.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace App\Module\GameItems\Validators;
  3. use App\Module\GameItems\Logics\ChestOpenCostLogic;
  4. use App\Module\GameItems\Repositorys\ItemChestOpenCostRepository;
  5. use App\Module\GameItems\Logics\Item as ItemLogic;
  6. use UCore\Validator;
  7. /**
  8. * 宝箱开启消耗验证器
  9. *
  10. * 验证用户是否有足够的资源开启宝箱
  11. */
  12. class ChestOpenCostValidator extends Validator
  13. {
  14. /**
  15. * 验证宝箱开启消耗
  16. *
  17. * @param mixed $value 物品ID
  18. * @param array $data 包含用户ID和数量的数组
  19. * @return bool 验证是否通过
  20. */
  21. public function validate(mixed $value, array $data): bool
  22. {
  23. $itemId = (int)$value;
  24. // 从 args 获取参数键名
  25. $userIdKey = $this->args[0] ?? 'user_id';
  26. $quantityKey = $this->args[1] ?? 'quantity';
  27. $userId = $data[$userIdKey] ?? null;
  28. $quantity = $data[$quantityKey] ?? 1;
  29. if (!$userId) {
  30. $this->addError('用户ID不能为空');
  31. return false;
  32. }
  33. try {
  34. // 创建消耗逻辑实例
  35. $chestOpenCostLogic = new ChestOpenCostLogic(
  36. app(ItemChestOpenCostRepository::class),
  37. new ItemLogic()
  38. );
  39. // 验证宝箱开启消耗
  40. list($isValid, $message, $costDetails) = $chestOpenCostLogic->validateChestOpenCosts($userId, $itemId, $quantity);
  41. if (!$isValid) {
  42. $this->addError($message);
  43. return false;
  44. }
  45. return true;
  46. } catch (\Exception $e) {
  47. $this->addError('验证宝箱开启消耗时发生错误: ' . $e->getMessage());
  48. return false;
  49. }
  50. }
  51. }