refactor: 使用FileManager统一文件操作

将分散在各处的文件操作统一封装到FileManager工具类中,包括文件读写、目录创建、JSON处理等操作
This commit is contained in:
LL
2025-12-12 14:22:40 +08:00
parent fbf39f81c2
commit 6c168246ca
6 changed files with 81 additions and 78 deletions

View File

@@ -1,5 +1,6 @@
<?php
// 基金监控系统管理页面
require_once 'utils/FileManager.php';
// 启动会话
session_start();
@@ -35,18 +36,14 @@ if (isset($_GET['action']) && $_GET['action'] === 'logout') {
// 保存注销日志
$log_file = 'data/operation_log.json';
if (file_exists($log_file)) {
$logs = json_decode(file_get_contents($log_file), true);
if (!is_array($logs)) {
$logs = [];
}
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);
}
file_put_contents($log_file, json_encode($logs, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
}
FileManager::saveJsonFile($log_file, $logs, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
// 销毁会话
session_unset();

View File

@@ -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的响应格式

36
api.php
View File

@@ -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;
}

View File

@@ -1,5 +1,6 @@
<?php
// 基金监控系统登录页面
require_once 'utils/FileManager.php';
// 初始化错误信息
$error = '';
@@ -41,19 +42,11 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
function saveLog($log_entry) {
$log_file = 'data/operation_log.json';
// 检查目录是否存在,不存在则创建
if (!file_exists(dirname($log_file))) {
mkdir(dirname($log_file), 0777, true);
}
// 确保目录存在
FileManager::ensureDirExists(dirname($log_file));
// 读取现有日志
$logs = [];
if (file_exists($log_file)) {
$content = file_get_contents($log_file);
if (!empty($content)) {
$logs = json_decode($content, true);
}
}
$logs = FileManager::loadJsonFile($log_file, []);
// 添加新日志
array_unshift($logs, $log_entry);
@@ -64,7 +57,7 @@ function saveLog($log_entry) {
}
// 保存日志
file_put_contents($log_file, json_encode($logs, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
FileManager::saveJsonFile($log_file, $logs, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
}
?>
<!DOCTYPE html>

View File

@@ -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) {

View File

@@ -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);
}
}
?>