| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- <?php
- namespace App\Module\GameItems\Validators;
- use App\Module\GameItems\Logics\ItemQuantity;
- use UCore\Validator;
- /**
- * 物品数量验证器
- *
- * 用于验证用户是否拥有足够数量的物品
- */
- class ItemQuantityValidator extends Validator
- {
- /**
- * 验证方法
- *
- * @param mixed $value 物品ID
- * @param array $data 包含用户ID和数量的数组
- * @return bool 验证是否通过
- *
- * 注意:
- * - $this->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;
- }
- }
- }
|