116 lines
3.6 KiB
PHP
116 lines
3.6 KiB
PHP
<?php
|
||
/**
|
||
* 文件管理工具类
|
||
* 提供通用的文件和目录操作功能,减少代码重复
|
||
*/
|
||
class FileManager {
|
||
|
||
/**
|
||
* 确保目录存在,如果不存在则创建
|
||
* @param string $dirPath 目录路径
|
||
* @param int $mode 目录权限(默认0755)
|
||
* @return bool 创建成功或目录已存在返回true,失败返回false
|
||
*/
|
||
public static function ensureDirExists($dirPath, $mode = 0755) {
|
||
if (!is_dir($dirPath)) {
|
||
return mkdir($dirPath, $mode, true);
|
||
}
|
||
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 文件路径
|
||
* @param mixed $default 默认值(文件不存在或解析失败时返回)
|
||
* @param callable|null $initCallback 初始化回调函数(文件不存在时调用)
|
||
* @return mixed 解析后的JSON数据或默认值
|
||
*/
|
||
public static function loadJsonFile($filePath, $default = [], callable $initCallback = null) {
|
||
if (!file_exists($filePath)) {
|
||
if ($initCallback) {
|
||
call_user_func($initCallback);
|
||
} else {
|
||
return $default;
|
||
}
|
||
}
|
||
|
||
$data = file_get_contents($filePath);
|
||
if (!$data) {
|
||
return $default;
|
||
}
|
||
|
||
$json = json_decode($data, true);
|
||
return is_array($json) ? $json : $default;
|
||
}
|
||
|
||
/**
|
||
* 保存JSON数据到文件
|
||
* @param string $filePath 文件路径
|
||
* @param mixed $data 要保存的数据
|
||
* @param int $flags JSON编码标志(默认JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
|
||
* @return bool 保存成功返回true,失败返回false
|
||
*/
|
||
public static function saveJsonFile($filePath, $data, $flags = JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) {
|
||
// 确保目录存在
|
||
$dirPath = dirname($filePath);
|
||
if (!self::ensureDirExists($dirPath)) {
|
||
return false;
|
||
}
|
||
|
||
return file_put_contents($filePath, json_encode($data, $flags)) !== false;
|
||
}
|
||
|
||
/**
|
||
* 删除文件
|
||
* @param string $filePath 文件路径
|
||
* @return bool 删除成功返回true,失败返回false
|
||
*/
|
||
public static function deleteFile($filePath) {
|
||
if (file_exists($filePath)) {
|
||
return unlink($filePath);
|
||
}
|
||
return true; // 文件不存在也视为删除成功
|
||
}
|
||
|
||
/**
|
||
* 获取文件修改时间
|
||
* @param string $filePath 文件路径
|
||
* @return int 文件修改时间戳(文件不存在返回0)
|
||
*/
|
||
public static function getFileMTime($filePath) {
|
||
if (file_exists($filePath)) {
|
||
return filemtime($filePath);
|
||
}
|
||
return 0;
|
||
}
|
||
|
||
/**
|
||
* 检查文件是否存在
|
||
* @param string $filePath 文件路径
|
||
* @return bool 文件存在返回true,否则返回false
|
||
*/
|
||
public static function fileExists($filePath) {
|
||
return file_exists($filePath);
|
||
}
|
||
}
|
||
?>
|