From 6c168246ca4b9341e752cb1b462b01d2ceaacbb6 Mon Sep 17 00:00:00 2001 From: LL Date: Fri, 12 Dec 2025 14:22:40 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E4=BD=BF=E7=94=A8FileManager?= =?UTF-8?q?=E7=BB=9F=E4=B8=80=E6=96=87=E4=BB=B6=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将分散在各处的文件操作统一封装到FileManager工具类中,包括文件读写、目录创建、JSON处理等操作 --- admin.php | 19 ++++++++---------- admin_api.php | 12 +++++------ api.php | 36 ++++++++++++++++----------------- login.php | 17 +++++----------- recommend_fund.php | 46 +++++++++++++++---------------------------- utils/FileManager.php | 29 +++++++++++++++++++++++++++ 6 files changed, 81 insertions(+), 78 deletions(-) diff --git a/admin.php b/admin.php index e37b799..008d3db 100644 --- a/admin.php +++ b/admin.php @@ -1,5 +1,6 @@ 500) { - $logs = array_slice($logs, 0, 500); - } - file_put_contents($log_file, json_encode($logs, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); + FileManager::ensureDirExists(dirname($log_file)); + $logs = FileManager::loadJsonFile($log_file, []); + array_unshift($logs, $log_entry); + // 限制日志数量 + if (count($logs) > 500) { + $logs = array_slice($logs, 0, 500); } + FileManager::saveJsonFile($log_file, $logs, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); // 销毁会话 session_unset(); diff --git a/admin_api.php b/admin_api.php index b12fe58..9e5871a 100644 --- a/admin_api.php +++ b/admin_api.php @@ -19,22 +19,22 @@ class FundAdminAPI extends ApiBase { FileManager::ensureDirExists('data'); // 初始化配置文件(如果不存在) - if (!file_exists($this->configFile)) { + if (!FileManager::fileExists($this->configFile)) { $this->initConfig(); } // 初始化操作日志文件(如果不存在) - if (!file_exists($this->operationFile)) { + if (!FileManager::fileExists($this->operationFile)) { $this->initOperationLog(); } // 初始化基金名称文件(如果不存在) - if (!file_exists($this->fundNamesFile)) { + if (!FileManager::fileExists($this->fundNamesFile)) { $this->initFundNames(); } // 初始化推荐基金文件(如果不存在) - if (!file_exists($this->recommendedFundsFile)) { + if (!FileManager::fileExists($this->recommendedFundsFile)) { $this->initRecommendedFunds(); } } @@ -142,7 +142,7 @@ class FundAdminAPI extends ApiBase { * 加载基金名称映射 */ private function loadFundNames() { - if (!file_exists($this->fundNamesFile)) { + if (!FileManager::fileExists($this->fundNamesFile)) { $this->initFundNames(); } @@ -719,7 +719,7 @@ class FundAdminAPI extends ApiBase { ] ]); - $response = file_get_contents($apiUrl, false, $context); + $response = FileManager::loadFile($apiUrl); if ($response) { // 处理不同API的响应格式 diff --git a/api.php b/api.php index d6d03dc..4f2cde3 100644 --- a/api.php +++ b/api.php @@ -41,32 +41,32 @@ class FundMonitorAPI extends ApiBase { FileManager::ensureDirExists('data'); // 初始化统计文件(如果不存在) - if (!file_exists($this->statsFile)) { + if (!FileManager::fileExists($this->statsFile)) { $this->initStats(); } // 初始化配置文件(如果不存在) - if (!file_exists($this->configFile)) { + if (!FileManager::fileExists($this->configFile)) { $this->initConfig(); } // 初始化历史数据文件(如果不存在) - if (!file_exists($this->historyFile)) { + if (!FileManager::fileExists($this->historyFile)) { $this->initHistory(); } // 初始化操作日志文件(如果不存在) - if (!file_exists($this->operationFile)) { + if (!FileManager::fileExists($this->operationFile)) { $this->initOperationLog(); } // 初始化每日数据文件(如果不存在) - if (!file_exists($this->dailyDataFile)) { + if (!FileManager::fileExists($this->dailyDataFile)) { $this->initDailyData(); } // 初始化邮件状态文件(如果不存在) - if (!file_exists($this->emailStatusFile)) { + if (!FileManager::fileExists($this->emailStatusFile)) { $this->initEmailStatus(); } @@ -78,8 +78,8 @@ class FundMonitorAPI extends ApiBase { * 加载邮箱配置 */ private function loadEmailConfig() { - if (file_exists($this->emailConfigFile)) { - $this->emailConfig = json_decode(file_get_contents($this->emailConfigFile), true); + if (FileManager::fileExists($this->emailConfigFile)) { + $this->emailConfig = FileManager::loadJsonFile($this->emailConfigFile); } else { // 如果配置文件不存在,使用默认配置 $this->initEmailConfig(); @@ -335,7 +335,7 @@ class FundMonitorAPI extends ApiBase { } else { $status['failed_count']++; // 保存错误日志 - file_put_contents('email_error_log.txt', date('Y-m-d H:i:s') . "\n" . $errorLog . "\n\n", FILE_APPEND); + FileManager::appendToFile('email_error_log.txt', date('Y-m-d H:i:s') . "\n" . $errorLog . "\n\n"); } $this->saveEmailStatus($status); @@ -609,12 +609,10 @@ class FundMonitorAPI extends ApiBase { */ private function getFromBatchCache($key) { $file = $this->getBatchCachePath($key); - if (!file_exists($file)) return false; + if (!FileManager::fileExists($file)) return false; // 过期判断 - if (time() - filemtime($file) > $this->batchCacheTTL) return false; - $raw = @file_get_contents($file); - if ($raw === false) return false; - $data = json_decode($raw, true); + if (time() - FileManager::getFileMTime($file) > $this->batchCacheTTL) return false; + $data = FileManager::loadJsonFile($file); return is_array($data) ? $data : false; } @@ -624,7 +622,7 @@ class FundMonitorAPI extends ApiBase { private function cacheBatchData($key, $data) { // 保证目录存在 FileManager::ensureDirExists($this->cacheDir); - @file_put_contents($this->getBatchCachePath($key), json_encode($data, JSON_UNESCAPED_UNICODE)); + FileManager::saveJsonFile($this->getBatchCachePath($key), $data, JSON_UNESCAPED_UNICODE); } @@ -640,7 +638,7 @@ class FundMonitorAPI extends ApiBase { * 保存访问记录 */ private function saveVisits($visits) { - return file_put_contents($this->dataFile, json_encode($visits)); + return FileManager::saveJsonFile($this->dataFile, $visits); } /** @@ -674,7 +672,7 @@ class FundMonitorAPI extends ApiBase { $visits = array_slice($visits, -1000); } - file_put_contents($this->dataFile, json_encode($visits, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); + FileManager::saveJsonFile($this->dataFile, $visits, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); // 更新统计 $this->updateStats($clientIP); @@ -789,7 +787,7 @@ class FundMonitorAPI extends ApiBase { // 保存唯一IP列表(用于快速计算) $stats['unique_ips'] = array_values($uniqueIPs); - file_put_contents($this->statsFile, json_encode($stats, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); + FileManager::saveJsonFile($this->statsFile, $stats, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); return $stats; } @@ -874,7 +872,7 @@ class FundMonitorAPI extends ApiBase { ] ]); - $response = @file_get_contents($apiUrl, false, $context); + $response = @FileManager::loadFile($apiUrl); if (!$response) { return false; } diff --git a/login.php b/login.php index f68c734..21cc862 100644 --- a/login.php +++ b/login.php @@ -1,5 +1,6 @@ diff --git a/recommend_fund.php b/recommend_fund.php index bff077f..5890d81 100644 --- a/recommend_fund.php +++ b/recommend_fund.php @@ -5,6 +5,8 @@ */ // 设置响应头 header('Content-Type: text/html; charset=utf-8'); +// 引入工具类 +require_once __DIR__ . '/utils/FileManager.php'; // 设置时区 date_default_timezone_set('Asia/Shanghai'); @@ -21,12 +23,8 @@ const MAX_TOTAL_FUNDS = 3000; // 系统最大基金数量 // 确保目录存在 function ensureDirsExist() { - if (!file_exists(DATA_DIR)) { - mkdir(DATA_DIR, 0755, true); - } - if (!file_exists(CACHE_DIR)) { - mkdir(CACHE_DIR, 0755, true); - } + FileManager::ensureDirExists(DATA_DIR); + FileManager::ensureDirExists(CACHE_DIR); } ensureDirsExist(); @@ -54,11 +52,7 @@ function getUserIP() { */ function loadRecommendedFunds() { $file = DATA_DIR . '/recommended_funds.json'; - if (file_exists($file)) { - $data = file_get_contents($file); - return json_decode($data, true) ?? []; - } - return []; + return FileManager::loadJsonFile($file, []); } /** @@ -81,7 +75,7 @@ function cleanNonExistentFunds() { // 如果有基金被移除,保存更新后的列表 if ($fundsRemoved > 0) { $file = DATA_DIR . '/recommended_funds.json'; - file_put_contents($file, json_encode($fundsToKeep, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); + FileManager::saveJsonFile($file, $fundsToKeep, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); // 记录清理日志 logAction('clean_nonexistent_funds', ['funds_removed' => $fundsRemoved]); @@ -97,17 +91,14 @@ function cleanNonExistentFunds() { */ function logAction($action, $data = []) { $logFile = DATA_DIR . '/recommend_logs.json'; - $logs = []; - if (file_exists($logFile)) { - $logs = json_decode(file_get_contents($logFile), true) ?? []; - } + $logs = FileManager::loadJsonFile($logFile, []); $logs[] = array_merge([ 'action' => $action, 'timestamp' => date('Y-m-d H:i:s') ], $data); - file_put_contents($logFile, json_encode($logs, JSON_PRETTY_PRINT)); + FileManager::saveJsonFile($logFile, $logs, JSON_PRETTY_PRINT); } /** @@ -126,21 +117,16 @@ function getFundCachePath($fundCode) { */ function getFundFromCache($fundCode) { $cacheFile = getFundCachePath($fundCode); - if (!file_exists($cacheFile)) { + if (!FileManager::fileExists($cacheFile)) { return false; } // 检查缓存是否过期 - if (time() - filemtime($cacheFile) > FUND_CACHE_TTL) { + if (time() - FileManager::getFileMTime($cacheFile) > FUND_CACHE_TTL) { return false; } - $data = file_get_contents($cacheFile); - if ($data === false) { - return false; - } - - $fundData = json_decode($data, true); + $fundData = FileManager::loadJsonFile($cacheFile); return is_array($fundData) ? $fundData : false; } @@ -151,7 +137,7 @@ function getFundFromCache($fundCode) { */ function cacheFundData($fundCode, $fundData) { $cacheFile = getFundCachePath($fundCode); - file_put_contents($cacheFile, json_encode($fundData, JSON_UNESCAPED_UNICODE)); + FileManager::saveJsonFile($cacheFile, $fundData, JSON_UNESCAPED_UNICODE); } /** @@ -169,7 +155,7 @@ function fetchFundDataFromAPI($fundCode) { ] ]); - $response = @file_get_contents($apiUrl, false, $context); + $response = @FileManager::loadFile($apiUrl); if (!$response) { return false; @@ -294,7 +280,7 @@ function saveRecommendedFund($fundCode, $ip) { // 保存到文件 $file = DATA_DIR . '/recommended_funds.json'; - file_put_contents($file, json_encode($funds, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); + FileManager::saveJsonFile($file, $funds, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); // 记录操作日志 logAction('recommend_fund', [ @@ -316,13 +302,13 @@ unset($_SESSION['message'], $_SESSION['messageType']); // 定期清理不存在的基金(每10分钟执行一次) $cleanupFile = DATA_DIR . '/last_cleanup.txt'; -$lastCleanup = @file_get_contents($cleanupFile); +$lastCleanup = @FileManager::loadFile($cleanupFile); $currentTime = time(); // 如果距离上次清理超过10分钟,执行清理 if (!$lastCleanup || ($currentTime - $lastCleanup) > 600) { $removedCount = cleanNonExistentFunds(); - file_put_contents($cleanupFile, $currentTime); + FileManager::saveFile($cleanupFile, $currentTime); // 如果有基金被清理,记录日志但不显示给用户 if ($removedCount > 0) { diff --git a/utils/FileManager.php b/utils/FileManager.php index 474f4dd..c3dc900 100644 --- a/utils/FileManager.php +++ b/utils/FileManager.php @@ -18,6 +18,26 @@ class FileManager { return true; } + /** + * 加载文件内容 + * @param string $filePath 文件路径 + * @return string|false 文件内容或false + */ + public static function loadFile($filePath) { + return file_get_contents($filePath); + } + + /** + * 保存文件内容 + * @param string $filePath 文件路径 + * @param string $content 文件内容 + * @param int $flags 标志位(默认0) + * @return int|false 成功返回写入的字节数,失败返回false + */ + public static function saveFile($filePath, $content, $flags = 0) { + return file_put_contents($filePath, $content, $flags); + } + /** * 加载JSON文件内容 * @param string $filePath 文件路径 @@ -83,5 +103,14 @@ class FileManager { } return 0; } + + /** + * 检查文件是否存在 + * @param string $filePath 文件路径 + * @return bool 文件存在返回true,否则返回false + */ + public static function fileExists($filePath) { + return file_exists($filePath); + } } ?> \ No newline at end of file