Attachment.php
2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<?php
namespace Lib\Imap\Parse;
use Lib\Imap\DataArray;
/**
 * 附件 数据 结构 类
 * @author:dc
 * @time 2024/9/21 16:57
 * Class Attachment
 * @package Lib\Imap\Parse
 */
class Attachment {
    public DataArray $data;
    public function __construct(DataArray $data){
        $this->data = $data;
    }
    /**
     * 读取文件的名称
     * @return string
     * @author:dc
     * @time 2024/9/21 17:01
     */
    public function getFilename():string {
        if($this->data->get('filename')){
            return $this->data->get('filename');
        }
        return $this->data->get('name');
    }
    /**
     * 获取文件的后缀 文件后缀
     * @return string
     * @author:dc
     * @time 2024/9/21 17:20
     */
    public function getExtension():string {
        if (isset($this->extension)){
            return $this->extension;
        }
        // 在 mime文件类型中查找
        if(is_file('mime.types') && $this->getFileType()){
            $type = file_get_contents('mime.types');
            $type = explode("\r\n",$type);
            foreach ($type as $item){
                if(stripos($item,$this->getFileType())===0){
                    list($t,$e) = explode(' ',$item,2);
                    $e = trim($e);
                    if($e){
                        $this->extension = $e;
                        return $e;
                    }
                    break;
                }
            }
        }
        // 如果还是没有 就从 文件名中获取
        $name = explode('.',$this->getFilename());
        $e = end($name);
        if($e){
            $this->extension = $e;
            return $e;
        }
        // 最后还是没有就 空
        return '';
    }
    /**
     * 文件内容
     * @return string
     * @author:dc
     * @time 2024/9/21 17:04
     */
    public function getContent():string {
        return $this->data->body;
    }
    /**
     * 文件类型
     * @return string
     * @author:dc
     * @time 2024/9/21 17:08
     */
    public function getFileType():string {
        return $this->data->get('content-type');
    }
    /**
     * 保存 文件到目录
     * @param string $filename 绝对路径的目录 文件名
     * @return bool
     * @author:dc
     * @time 2024/9/21 17:10
     */
    public function save(string $filename):bool {
        $path = dirname($filename);
        if(!is_dir($path)){
            @mkdir($path,0775,true);
        }
        // 保存文件
        if(@file_put_contents($filename,$this->getContent())){
            return true;
        }
        return false;
    }
}