Files
lgp-admin-plus-api/app/Models/FileModel.php

98 lines
3.6 KiB
PHP
Raw Normal View History

2025-05-12 00:19:35 +08:00
<?php
namespace App\Models;
use App\BaseApp\BaseModel;
/**
* 文件 / 素材表nl_file
*
* 原表只是上传流水user_id + url。素材库扩了对象键、体积、哈希与引用计数之后
* 它同时充当素材主表type / source 的取值被同步、回收、前端筛选三处共用,
* 所以固化成常量,免得三边各写一套魔法数字、还各写错一个。
*/
2025-05-12 09:04:46 +08:00
class FileModel extends BaseModel
2025-05-12 00:19:35 +08:00
{
/*
* type 取值。0~4 是老表原有语义5、6 是素材库补的:
* 图册 PDF、报价 Excel 这类文件原先全落在「其他」里没法筛。
*/
public const TYPE_IMAGE = 0;
public const TYPE_VIDEO = 1;
public const TYPE_AUDIO = 2;
public const TYPE_EXCEL = 3;
public const TYPE_ARCHIVE = 4;
public const TYPE_DOCUMENT = 5;
public const TYPE_OTHER = 6;
/** source经上传接口进来的 */
public const SOURCE_UPLOAD = 0;
/** source从 OSS 反向列举补录的历史文件 */
public const SOURCE_OSS = 1;
2025-05-12 00:19:35 +08:00
2025-05-12 09:04:46 +08:00
protected $table = 'file';
protected $guarded = [];
2025-05-12 00:19:35 +08:00
/**
* 数值列显式转型MySQL 驱动会把 bigint / int 读成字符串,
* 前端拿 size 做体积换算、拿 ref_count 判断能否回收时会被字符串坑到
2025-05-12 00:19:35 +08:00
*
* created_at / updated_at 不在此列BaseModel 已经用访问器格式化成了日期串,
* 再加 cast 只会让两套逻辑互相打架
2025-05-12 00:19:35 +08:00
*/
protected $casts = [
'user_id' => 'integer',
'oss_config_id' => 'integer',
'folder_id' => 'integer',
'type' => 'integer',
'size' => 'integer',
'width' => 'integer',
'height' => 'integer',
'ref_count' => 'integer',
'last_scan_at' => 'integer',
'source' => 'integer',
];
2026-08-19 08:16:49 +08:00
/**
* 从对象键取出能落库的扩展名(小写、不带点、最长 20
*
* 七牛历史上会把处理参数写进文件名:
* b_xxx.jpeg~tplv-a9rns2rl98-downsize_watermark_1_5
* pathinfo 会把整段 ~ 后面都当成扩展名varchar(20) 直接截断报错,
* 整批 insert 跟着失败。这里先剥查询串和 ~ 后缀,再取真正的后缀。
* 微信保存的 .pic / .pic_hd jpg 认,否则会被打成「其他」。
*/
public static function extOfKey(string $key): string
{
$name = basename(str_replace('\\', '/', $key));
$cut = strpbrk($name, '?~#');
if ($cut !== false) {
$name = substr($name, 0, strlen($name) - strlen($cut));
}
$ext = strtolower(trim((string) pathinfo($name, PATHINFO_EXTENSION), " \t\n\r\0\x0B."));
if ($ext === 'pic' || $ext === 'pic_hd') {
return 'jpg';
}
return $ext === '' ? '' : substr($ext, 0, 20);
}
/**
* 扩展名归类到 type
*
* OSS 反向同步时手上只有对象键,没有上传时的 MIME只能按扩展名判断
*/
public static function typeOfExt(string $ext): int
{
return match (strtolower(trim($ext, " \t\n\r\0\x0B."))) {
2026-08-19 08:16:49 +08:00
'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg', 'ico', 'avif', 'heic', 'pic', 'pic_hd' => self::TYPE_IMAGE,
'mp4', 'mov', 'avi', 'mkv', 'flv', 'wmv', 'webm', 'm3u8', 'ts' => self::TYPE_VIDEO,
'mp3', 'wav', 'aac', 'flac', 'ogg', 'm4a', 'amr' => self::TYPE_AUDIO,
'xls', 'xlsx', 'csv' => self::TYPE_EXCEL,
'zip', 'rar', '7z', 'tar', 'gz', 'bz2' => self::TYPE_ARCHIVE,
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'txt', 'md' => self::TYPE_DOCUMENT,
default => self::TYPE_OTHER,
};
}
2025-05-12 00:19:35 +08:00
}