Skip to main content

File

Struct File 

Source
pub struct File { /* private fields */ }
Expand description

文件类 — 对齐 PHP think\File(基于 SplFileInfo

PHP 第 22-46 行:

class File extends SplFileInfo {
    protected $hash = [];
    protected $hashName;
    protected $extension;
    public function __construct(string $path, bool $checkPath = true) {
        if ($checkPath && !is_file($path)) {
            throw new FileException(sprintf('The file "%s" does not exist', $path));
        }
        parent::__construct($path);
    }
}

Implementations§

Source§

impl File

Source

pub fn new<P>(path: P, check_path: bool) -> Result<File, UploadError>
where P: AsRef<Path>,

创建 File 实例 — 对齐 PHP File::__construct 第 39-46 行

check_path = true 时检查文件是否存在,不存在返回 UploadError::FileNotFound

Source

pub fn new_unchecked<P>(path: P) -> File
where P: AsRef<Path>,

不检查路径创建实例 — 对齐 PHP 第 138 行 new self($target, false)

Source

pub fn path(&self) -> &Path

获取文件路径 — 对齐 PHP SplFileInfo::getPathname()

Source

pub fn path_name(&self) -> String

获取文件路径字符串

Source

pub fn hash(&mut self, algo: HashAlgo) -> Result<String, UploadError>

获取文件哈希 — 对齐 PHP File::hash($type) 第 54-61 行

PHP 行为:

public function hash(string $type = 'sha1'): string {
    if (!isset($this->hash[$type])) {
        $this->hash[$type] = hash_file($type, $this->getPathname());
    }
    return $this->hash[$type];
}
Source

pub fn md5(&mut self) -> Result<String, UploadError>

获取文件 MD5 — 对齐 PHP File::md5() 第 68-71 行

Source

pub fn sha1(&mut self) -> Result<String, UploadError>

获取文件 SHA1 — 对齐 PHP File::sha1() 第 78-81 行

Source

pub fn get_mime(&self) -> Result<String, UploadError>

获取文件 MIME — 对齐 PHP File::getMime() 第 88-93 行

PHP 行为:使用 finfo_open(FILEINFO_MIME_TYPE) + finfo_file() 检测 MIME。 Rust 端:优先用 infer crate 从内容检测,回退到 mime_guess 从扩展名猜测。

Source

pub fn move_to<P>( &mut self, directory: P, name: Option<&str>, ) -> Result<File, UploadError>
where P: AsRef<Path>,

移动文件 — 对齐 PHP File::move() 第 102-118 行

PHP 行为:

  1. 获取 target 文件
  2. rename($this->getPathname(), $target) 移动文件
  3. 失败抛 FileException
  4. chmod($target, 0666 & ~umask()) 设置权限
  5. 返回新 File 实例
Source

pub fn extension(&self) -> String

文件扩展名 — 对齐 PHP File::extension() 第 159-162 行

PHP 行为:return $this->getExtension();SplFileInfo::getExtension() 返回最后点后的部分)

Source

pub fn set_extension(&mut self, extension: &str)

指定保存文件的扩展名 — 对齐 PHP File::setExtension() 第 169-172 行

Source

pub fn hash_name(&mut self, rule: HashNameRule) -> Result<String, UploadError>

自动生成文件名 — 对齐 PHP File::hashName($rule) 第 180-203 行

PHP 行为:

public function hashName($rule = ''): string {
    if (!$this->hashName) {
        if ($rule instanceof \Closure) {
            $this->hashName = call_user_func_array($rule, [$this]);
        } else {
            switch (true) {
                case in_array($rule, hash_algos()):
                    $hash = $this->hash($rule);
                    $this->hashName = substr($hash, 0, 2) . DIRECTORY_SEPARATOR . substr($hash, 2);
                    break;
                case is_callable($rule):
                    $this->hashName = call_user_func($rule);
                    break;
                default:
                    $this->hashName = date('Ymd') . DIRECTORY_SEPARATOR . md5(microtime(true) . $this->getPathname());
                    break;
            }
        }
    }
    $extension = $this->extension ?? $this->extension();
    return $this->hashName . ($extension ? '.' . $extension : '');
}

Rust 端简化:只支持 DefaultHash(algo) 两种规则。

Source

pub fn basename(&self) -> String

获取文件名(不含目录) — 对齐 PHP SplFileInfo::getBasename()

Trait Implementations§

Source§

impl Clone for File

Source§

fn clone(&self) -> File

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for File

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for File

§

impl RefUnwindSafe for File

§

impl Send for File

§

impl Sync for File

§

impl Unpin for File

§

impl UnsafeUnpin for File

§

impl UnwindSafe for File

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more