<?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 $path 绝对路径的目录 * @param string $filename 文件名 * @return bool|string * @author:dc * @time 2024/9/21 17:10 */ public function save(string $path, string $filename = ''):bool|string { $filename = $filename ? : (md5($this->getContent()).'.'.$this->getExtension()); if(!is_dir($path)){ @mkdir($path,0775,true); } $path = rtrim($path,'/').'/'; // 保存文件 if(@file_put_contents($path.$filename,$this->getContent())){ return $path.$filename; } return false; } /** * 读取 附件的内容id ,如果附件是 inline 这个是必须的 * @return string * @author:dc * @time 2024/9/23 10:27 */ public function getContentId(){ $contentId = $this->data->get('Content-ID'); return trim(str_replace(['"','<','>'],'',$contentId)); } }