CraftMaterialsValidator.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace App\Module\GameItems\Validators;
  3. use App\Module\GameItems\Services\ItemService;
  4. use UCore\Validator;
  5. /**
  6. * 合成材料验证器
  7. *
  8. * 验证用户是否有足够的材料进行合成
  9. */
  10. class CraftMaterialsValidator 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. try {
  33. // 检查每个材料是否充足
  34. foreach ($recipe->materials as $material) {
  35. $requiredQuantity = $material->quantity * $quantity;
  36. // 获取用户拥有的该物品数量
  37. $userItems = ItemService::getUserItems($userId, ['item_id' => $material->item_id]);
  38. $totalQuantity = $userItems->sum('quantity');
  39. if ($totalQuantity < $requiredQuantity) {
  40. $itemName = $material->item->name ?? "物品ID:{$material->item_id}";
  41. $this->addError("材料不足:{$itemName},需要{$requiredQuantity}个,当前拥有{$totalQuantity}个");
  42. return false;
  43. }
  44. }
  45. return true;
  46. } catch (\Exception $e) {
  47. $this->addError('验证合成材料时发生错误: ' . $e->getMessage());
  48. return false;
  49. }
  50. }
  51. }