<?php

namespace Application\Service\Extension\Uploader;

class Image
{
    /**
     * 文件名称(text.jpg => text.jpg)
     * @var string|mixed
     */
    public string $name;
    /**
     * 错误代码
     * @var int|mixed
     */
    public int $error;
    /**
     * 文件大小
     * @var int|mixed
     */
    public int $size;
    /**
     * 文件名(text.jpg => text)
     * @var string
     */
    public string $baseName;
    /**
     * 临时文件地址
     * @var string|mixed
     */
    public string $tmpName;
    /**
     * 文件类型
     * @var string|mixed
     */
    public string $type;
    /**
     * 文件后缀
     * @var string
     */
    public string $extension;

    public function __construct($file)
    {
        $this->name = $file['name'];
        $this->baseName = $this->getBaseName();
        $this->error = $file['error'];
        $this->size = $file['size'];
        $this->tmpName = $file['tmp_name'];
        $this->type = $file['type'];
        $this->extension = $this->getExtension();
    }

    /**
     * 获取文件名
     * @return string
     */
    public function getBaseName(): string
    {
        $pathInfo = pathinfo('_' . $this->name, PATHINFO_FILENAME);
        return mb_substr($pathInfo, 1, mb_strlen($pathInfo, '8bit'), '8bit');
    }

    /**
     * 获取文件后缀
     * @return string
     */
    public function getExtension()
    {
        return strtolower(pathinfo($this->name, PATHINFO_EXTENSION));
    }

    /**
     * 是否发生了上传错误
     * @return bool
     */
    public function getHasError()
    {
        return $this->error != UPLOAD_ERR_OK;
    }

    /**
     * 获取上传错误原因
     * @return string|void
     */
    public function getErrorString()
    {
        switch ($this->error) {
            case UPLOAD_ERR_INI_SIZE:
                return '文件上传超过了php.ini中upload_max_filesize的值。';
            case UPLOAD_ERR_FORM_SIZE:
                return '文件大小超过了HTML表单中MAX_FILE_SIZE选项的指定值。';
            case UPLOAD_ERR_PARTIAL:
                return '文件只有部分被上传。';
            case UPLOAD_ERR_NO_FILE:
                return '没有文件被上传。';
            case UPLOAD_ERR_NO_TMP_DIR:
                return '找不到临时文件夹。';
            case UPLOAD_ERR_CANT_WRITE:
                return '文件写入失败。';
        }
    }
}