| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- <?php
- namespace App\Module\Farm\Validators;
- use App\Module\GameItems\Services\ItemService;
- use UCore\Validator;
- /**
- * 种子归属验证器
- *
- * 验证用户是否拥有指定的种子
- */
- class SeedOwnershipValidator 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] ?? 'item_instance_id';
- $userId = $data[$userIdKey] ?? null;
- $instanceId = $data[$instanceIdKey] ?? null;
- if (!$userId) {
- $this->addError('用户ID不能为空');
- return false;
- }
- try {
- // 检查用户是否拥有该种子
- $userItems = ItemService::getUserItems($userId, ['item_id' => $itemId]);
-
- if ($userItems->isEmpty()) {
- $this->addError('您没有该种子');
- return false;
- }
- // 如果指定了实例ID,检查特定实例
- if ($instanceId > 0) {
- $userItem = ItemService::getUserItem($userId, $itemId, $instanceId);
- if (!$userItem) {
- $this->addError('指定的种子实例不存在');
- return false;
- }
- if ($userItem->quantity <= 0) {
- $this->addError('种子数量不足');
- return false;
- }
- } else {
- // 检查总数量
- $totalQuantity = $userItems->sum('quantity');
- if ($totalQuantity <= 0) {
- $this->addError('种子数量不足');
- return false;
- }
- }
- return true;
- } catch (\Exception $e) {
- $this->addError('验证种子归属时发生错误: ' . $e->getMessage());
- return false;
- }
- }
- }
|