70 lines
2.2 KiB
PHP
70 lines
2.2 KiB
PHP
|
<?php
|
||
|
|
||
|
namespace app\model;
|
||
|
|
||
|
use Exception;
|
||
|
use think\exception\ValidateException;
|
||
|
|
||
|
class Attachment extends Base
|
||
|
{
|
||
|
protected $name = 'file';
|
||
|
|
||
|
public const TYPE_DIR = 'dir';//目录
|
||
|
public const TYPE_IMG = 'image';//图片
|
||
|
public const TYPE_VIDEO = 'video';//视频
|
||
|
public const TYPE_FILE = 'file';//文件
|
||
|
|
||
|
public const ROOT_NAME = 'storage';//根目录名称
|
||
|
public const ROOT_PATH = "/".self::ROOT_NAME;//文件存放根路径
|
||
|
|
||
|
public static function list(): array
|
||
|
{
|
||
|
$where[] = ['src', 'like', '%'.self::ROOT_PATH."/"];
|
||
|
return self::findList($where);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 路径目录处理 会逐级检查路径上所有目录是否存在 不存在的目录全部创建[创建到数据库]
|
||
|
*
|
||
|
* @throws Exception
|
||
|
*/
|
||
|
public static function pathDirHandle(string $path): bool
|
||
|
{
|
||
|
$pathInfo = pathinfo($path);
|
||
|
$fullPath = isset($pathInfo['extension']) ? $pathInfo['dirname'] : $pathInfo['dirname']."/".$pathInfo['filename'];
|
||
|
|
||
|
// 全路径 如 /storage/dir1/dir2/dir3/dir4/ 注意前后都有/
|
||
|
$fullPath = $fullPath."/";
|
||
|
|
||
|
$pathArr = explode("/", trim($fullPath, "/"));
|
||
|
|
||
|
$insert = [];
|
||
|
$now = date('Y-m-d H:i:s');
|
||
|
try {
|
||
|
// 检测全路径上所有目录是否存在 不存在则创建
|
||
|
foreach ($pathArr as $k => $p) {
|
||
|
$currentPath = '/';
|
||
|
$currentArr = array_slice($pathArr, 0, $k);
|
||
|
if ($currentArr) {
|
||
|
$currentPath = "/".implode('/', $currentArr)."/";
|
||
|
}
|
||
|
if ($currentPath != '/' && self::where('path', $currentPath)->where('name', $p)->count() <= 0) {
|
||
|
$arr = [];
|
||
|
$arr['path'] = $currentPath;
|
||
|
$arr['name'] = $p;
|
||
|
$arr['created_at'] = $now;
|
||
|
$arr['is_dir'] = self::COMMON_ON;
|
||
|
$arr['type'] = self::TYPE_DIR;
|
||
|
|
||
|
$insert[] = $arr;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
(new self())->saveAll($insert);
|
||
|
return true;
|
||
|
} catch (Exception $e) {
|
||
|
return false;
|
||
|
}
|
||
|
}
|
||
|
}
|