cachePrefix}{$itemId}"; $cachedResult = Cache::get($cacheKey); if ($cachedResult !== null) { if (!$cachedResult) { $this->addError("物品({$itemId})不是宠物口粮"); } return $cachedResult; } try { // 创建物品服务实例 $itemService = new ItemService(); // 获取物品信息 $item = $itemService->getItemInfo($itemId); if (!$item) { // 物品不存在 Cache::put($cacheKey, false, $this->cacheExpiration); $this->addError("物品({$itemId})不存在"); return false; } // 检查物品是否有宠物相关属性 $isPetFood = $this->checkPetFoodAttributes($item); // 缓存结果 Cache::put($cacheKey, $isPetFood, $this->cacheExpiration); if (!$isPetFood) { $this->addError("物品({$itemId})不是宠物口粮"); } return $isPetFood; } catch (\Exception $e) { Log::error('验证宠物口粮失败', [ 'item_id' => $itemId, 'error' => $e->getMessage() ]); $this->addError('验证过程发生错误: ' . $e->getMessage()); return false; } } /** * 检查物品是否具有宠物口粮属性 * * @param object|array $item 物品信息 * @return bool 是否具有宠物口粮属性 */ protected function checkPetFoodAttributes($item): bool { // 检查物品是否有pet_power或pet_exp属性 $numericAttributes = $item->numeric_attributes ?? []; if (is_string($numericAttributes)) { $numericAttributes = json_decode($numericAttributes, true) ?? []; } elseif (is_object($numericAttributes)) { $numericAttributes = (array)$numericAttributes; } // 检查是否有宠物相关属性 $hasPetPower = isset($numericAttributes['pet_power']) && $numericAttributes['pet_power'] > 0; $hasPetExp = isset($numericAttributes['pet_exp']) && $numericAttributes['pet_exp'] > 0; // 如果有任一宠物属性,则认为是宠物口粮 return $hasPetPower || $hasPetExp; } /** * 获取物品的宠物属性 * * @param int $itemId 物品ID * @return array 宠物属性 */ public function getPetFoodAttributes(int $itemId): array { try { // 创建物品服务实例 $itemService = new ItemService(); // 获取物品信息 $item = $itemService->getItemInfo($itemId); if (!$item) { return [ 'pet_power' => 0, 'pet_exp' => 0 ]; } // 获取物品的宠物属性 $numericAttributes = $item->numeric_attributes ?? []; if (is_string($numericAttributes)) { $numericAttributes = json_decode($numericAttributes, true) ?? []; } elseif (is_object($numericAttributes)) { $numericAttributes = (array)$numericAttributes; } return [ 'pet_power' => $numericAttributes['pet_power'] ?? 0, 'pet_exp' => $numericAttributes['pet_exp'] ?? 0 ]; } catch (\Exception $e) { Log::error('获取宠物口粮属性失败', [ 'item_id' => $itemId, 'error' => $e->getMessage() ]); return [ 'pet_power' => 0, 'pet_exp' => 0 ]; } } /** * 清除物品的缓存结果 * * @param int $itemId 物品ID * @return void */ public function clearCache(int $itemId): void { $cacheKey = "{$this->cachePrefix}{$itemId}"; Cache::forget($cacheKey); } /** * 清除所有缓存结果 * * @return void */ public function clearAllCache(): void { // 注意:这种方式可能不适用于所有缓存驱动 // 对于生产环境,可能需要更精细的缓存清理方式 $pattern = "{$this->cachePrefix}*"; // 使用Redis的模式匹配删除键(如果使用Redis缓存) if (config('cache.default') === 'redis') { $redis = Cache::getRedis(); $keys = $redis->keys($pattern); if (!empty($keys)) { $redis->del($keys); } } else { // 对于其他缓存驱动,可能需要单独实现 Log::warning('清除所有宠物口粮验证缓存可能不完全', [ 'cache_driver' => config('cache.default') ]); } } }