| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- <?php
- namespace App\Module\GameItems\Validators;
- use App\Module\GameItems\Services\ItemService;
- use UCore\Validator;
- /**
- * 物品归属验证器
- *
- * 验证用户是否拥有指定的物品和数量
- */
- class ItemOwnershipValidator extends Validator
- {
- /**
- * 验证物品归属
- *
- * @param mixed $value 物品ID
- * @param array $data 包含用户ID、实例ID和数量的数组
- * @return bool 验证是否通过
- */
- public function validate(mixed $value, array $data): bool
- {
- $itemId = (int)$value;
-
- // 从 args 获取参数键名
- $userIdKey = $this->args[0] ?? 'user_id';
- $instanceIdKey = $this->args[1] ?? 'instance_id';
- $quantityKey = $this->args[2] ?? 'quantity';
- $userId = $data[$userIdKey] ?? null;
- $instanceId = $data[$instanceIdKey] ?? 0;
- $requiredQuantity = $data[$quantityKey] ?? 1;
- if (!$userId) {
- $this->addError('用户ID不能为空');
- return false;
- }
- try {
- // 如果指定了实例ID,检查特定实例
- if ($instanceId > 0) {
- $userItem = ItemService::getUserItem($userId, $itemId, $instanceId);
- if (!$userItem) {
- $this->addError('指定的物品实例不存在');
- return false;
- }
- if ($userItem->quantity < $requiredQuantity) {
- $this->addError("物品数量不足,需要{$requiredQuantity}个,当前拥有{$userItem->quantity}个");
- return false;
- }
- } else {
- // 检查用户是否拥有足够数量的该物品
- $userItems = ItemService::getUserItems($userId, ['item_id' => $itemId]);
-
- if ($userItems->isEmpty()) {
- $this->addError('您没有该物品');
- return false;
- }
- $totalQuantity = $userItems->sum('quantity');
- if ($totalQuantity < $requiredQuantity) {
- $this->addError("物品数量不足,需要{$requiredQuantity}个,当前拥有{$totalQuantity}个");
- return false;
- }
- }
- return true;
- } catch (\Exception $e) {
- $this->addError('验证物品归属时发生错误: ' . $e->getMessage());
- return false;
- }
- }
- }
|