args[0] 可以指定用户ID的键名,默认为 'user_id' * - $this->args[1] 可以指定数量的键名,默认为 'quantity' * - $this->args[2] 可以指定实例ID的键名,默认为 'instance_id' * - $this->args[3] 可以指定是否包含所有类型物品的标志,默认为 false(只验证普通物品) */ public function validate(mixed $value, array $data): bool { $itemId = (int)$value; // 从 args 获取字段键名,如果未提供则使用默认值 $userIdKey = $this->args[0] ?? 'user_id'; $quantityKey = $this->args[1] ?? 'quantity'; $instanceIdKey = $this->args[2] ?? 'instance_id'; $includeAllTypes = $this->args[3] ?? false; $userId = $data[$userIdKey] ?? 0; $quantity = $data[$quantityKey] ?? 1; $instanceId = $data[$instanceIdKey] ?? null; // 验证参数 if ($itemId <= 0) { $this->addError('物品ID无效'); return false; } if ($userId <= 0) { $this->addError('用户ID无效'); return false; } if ($quantity <= 0) { $this->addError('物品数量必须大于0'); return false; } try { // 根据不同情况进行验证 if ($instanceId !== null) { // 验证特定实例物品 $hasInstance = ItemQuantity::hasInstanceItem($userId, $itemId, $instanceId); if (!$hasInstance) { $this->addError("用户不拥有指定的实例物品(ID: {$instanceId})"); return false; } return true; } else if ($includeAllTypes) { // 验证所有类型物品(普通物品和实例物品)的总数量 $totalQuantity = ItemQuantity::getUserTotalItemQuantity($userId, $itemId); if ($totalQuantity < $quantity) { $this->addError("物品总数量不足,需要{$quantity}个,但只有{$totalQuantity}个"); return false; } return true; } else { // 只验证普通物品数量 $normalQuantity = ItemQuantity::getUserItemQuantity($userId, $itemId); if ($normalQuantity < $quantity) { $this->addError("普通物品 $itemId 数量不足,需要{$quantity}个,但只有{$normalQuantity}个"); return false; } return true; } } catch (\Exception $e) { $this->addError('验证物品数量时发生错误: ' . $e->getMessage()); return false; } } }