CraftConsumeValidator.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace App\Module\GameItems\Validators;
  3. use App\Module\Game\Services\ConsumeService;
  4. use UCore\Validator;
  5. /**
  6. * 合成消耗验证器
  7. *
  8. * 基于组系统验证用户是否有足够的资源进行合成
  9. */
  10. class CraftConsumeValidator 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. $quantityKey = $this->args[1] ?? 'quantity';
  24. $recipeKey = $this->args[2] ?? 'recipe';
  25. $userId = $data[$userIdKey] ?? null;
  26. $quantity = $data[$quantityKey] ?? 1;
  27. $recipe = $this->validation->$recipeKey ?? null;
  28. if (!$userId || !$recipe) {
  29. $this->addError('验证合成消耗时缺少必要参数');
  30. return false;
  31. }
  32. // 检查配方是否有消耗组
  33. if (!$recipe->consume_group_id) {
  34. $this->addError('配方未配置消耗组');
  35. return false;
  36. }
  37. try {
  38. // 使用消耗组服务检查消耗条件
  39. $checkResult = ConsumeService::checkConsume($userId, $recipe->consume_group_id, $quantity);
  40. if (!$checkResult->success) {
  41. $this->addError($checkResult->message);
  42. return false;
  43. }
  44. return true;
  45. } catch (\Exception $e) {
  46. $this->addError('验证合成消耗时发生错误: ' . $e->getMessage());
  47. return false;
  48. }
  49. }
  50. }