refactor:将 file_unit_to_byte 归类到 Filesystem 类

This commit is contained in:
妙码生花 2023-06-26 04:01:31 +08:00
parent 065ccc78c1
commit 52b9a3bf42
3 changed files with 19 additions and 20 deletions

View File

@ -1,6 +1,7 @@
<?php
// 应用公共文件
use ba\Filesystem;
use think\Response;
use think\facade\Db;
use think\facade\Lang;
@ -332,7 +333,7 @@ if (!function_exists('get_upload_config')) {
function get_upload_config(): array
{
$uploadConfig = Config::get('upload');
$uploadConfig['maxsize'] = file_unit_to_byte($uploadConfig['maxsize']);
$uploadConfig['maxsize'] = Filesystem::fileUnitToByte($uploadConfig['maxsize']);
$upload = request()->upload;
if (!$upload) {
@ -343,21 +344,3 @@ if (!function_exists('get_upload_config')) {
return array_merge($upload, $uploadConfig);
}
}
if (!function_exists('file_unit_to_byte')) {
/**
* 将一个文件单位转为字节
* @param string $unit 将b、kb、m、mb、g、gb的单位转为 byte
* @return int byte
*/
function file_unit_to_byte(string $unit): int
{
preg_match('/([0-9\.]+)(\w+)/', $unit, $matches);
if (!$matches) {
return 0;
}
$typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
return (int)($matches[1] * pow(1024, $typeDict[strtolower($matches[2])] ?? 0));
}
}

View File

@ -5,6 +5,7 @@ namespace app\common\library;
use Throwable;
use ba\Random;
use think\File;
use ba\Filesystem;
use think\Exception;
use think\facade\Config;
use think\file\UploadedFile;
@ -140,7 +141,7 @@ class Upload
*/
protected function checkSize(): void
{
$size = file_unit_to_byte($this->config['maxsize']);
$size = Filesystem::fileUnitToByte($this->config['maxsize']);
if ($this->fileInfo['size'] > $size) {
throw new Exception(__('The uploaded file is too large (%sMiB), Maximum file size:%sMiB', [
round($this->fileInfo['size'] / pow(1024, 2), 2),

View File

@ -221,4 +221,19 @@ class Filesystem
}
return $fileList;
}
/**
* 将一个文件单位转为字节
* @param string $unit 将b、kb、m、mb、g、gb的单位转为 byte
* @return int byte
*/
public static function fileUnitToByte(string $unit): int
{
preg_match('/([0-9.]+)(\w+)/', $unit, $matches);
if (!$matches) {
return 0;
}
$typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
return (int)($matches[1] * pow(1024, $typeDict[strtolower($matches[2])] ?? 0));
}
}