| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- <?php
- namespace App\Module\Farm\Validators;
- use App\Module\GameItems\Services\ItemService;
- use UCore\Validator;
- /**
- * 铲除工具验证器
- *
- * 验证用户是否拥有铲除工具(如果需要)
- */
- class RemoveToolValidator extends Validator
- {
- /**
- * 验证铲除工具
- *
- * @param mixed $value 工具物品ID
- * @param array $data 包含用户ID的数组
- * @return bool 验证是否通过
- */
- public function validate(mixed $value, array $data): bool
- {
- $toolItemId = (int)$value;
-
- // 如果没有提供工具ID,则跳过验证(允许不使用工具)
- if ($toolItemId <= 0) {
- return true;
- }
- // 从 args 获取用户ID的键名
- $userIdKey = $this->args[0] ?? 'user_id';
- $userId = $data[$userIdKey] ?? null;
- if (!$userId) {
- $this->addError('用户ID不能为空');
- return false;
- }
- try {
- // 检查用户是否拥有该工具
- $userItems = ItemService::getUserItems($userId, ['item_id' => $toolItemId]);
-
- if ($userItems->isEmpty()) {
- $this->addError('您没有该铲除工具');
- return false;
- }
- $totalQuantity = $userItems->sum('quantity');
- if ($totalQuantity <= 0) {
- $this->addError('铲除工具数量不足');
- return false;
- }
- return true;
- } catch (\Exception $e) {
- $this->addError('验证铲除工具时发生错误: ' . $e->getMessage());
- return false;
- }
- }
- }
|