| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- <?php
- namespace App\Module\GameItems\Validators;
- use App\Module\GameItems\Services\ItemService;
- use UCore\Validator;
- /**
- * 合成材料验证器
- *
- * 验证用户是否有足够的材料进行合成
- */
- class CraftMaterialsValidator extends Validator
- {
- /**
- * 验证合成材料
- *
- * @param mixed $value 配方ID
- * @param array $data 包含用户ID和数量的数组
- * @return bool 验证是否通过
- */
- public function validate(mixed $value, array $data): bool
- {
- // 从 args 获取参数键名
- $userIdKey = $this->args[0] ?? 'user_id';
- $quantityKey = $this->args[1] ?? 'quantity';
- $recipeKey = $this->args[2] ?? 'recipe';
- $userId = $data[$userIdKey] ?? null;
- $quantity = $data[$quantityKey] ?? 1;
- $recipe = $this->validation->$recipeKey ?? null;
- if (!$userId || !$recipe) {
- $this->addError('验证合成材料时缺少必要参数');
- return false;
- }
- try {
- // 检查每个材料是否充足
- foreach ($recipe->materials as $material) {
- $requiredQuantity = $material->quantity * $quantity;
-
- // 获取用户拥有的该物品数量
- $userItems = ItemService::getUserItems($userId, ['item_id' => $material->item_id]);
- $totalQuantity = $userItems->sum('quantity');
- if ($totalQuantity < $requiredQuantity) {
- $itemName = $material->item->name ?? "物品ID:{$material->item_id}";
- $this->addError("材料不足:{$itemName},需要{$requiredQuantity}个,当前拥有{$totalQuantity}个");
- return false;
- }
- }
- return true;
- } catch (\Exception $e) {
- $this->addError('验证合成材料时发生错误: ' . $e->getMessage());
- return false;
- }
- }
- }
|