Address.php 1.7 KB
<?php

namespace Lib\Imap\Parse;

/**
 * @author:dc
 * @time 2024/9/11 11:17
 * Class Address
 * @package Imap\Parse
 */
class Address {

    public string $name = '';

    public string $email = '';

    private string $raw;

    private function __construct(string $address){
        $this->raw = $address;
        if($this->raw){
            $this->parse();
        }
    }

    /**
     * 创建一个地址类
     * @param string $address
     * @return static
     * @author:dc
     * @time 2024/9/11 11:37
     */
    public static function make(string $address):self {
        return new self($address);
    }

    /**
     * 解析地址
     * @author:dc
     * @time 2024/9/11 11:39
     */
    private function parse(){

        $email = self::pregEmail($this->raw);

        if(!empty($email)){
            $this->email = $email;
            $this->name = trim(str_replace([$email,'"','<','>','&gt;','&lt;'],'',$this->raw));
        }
        if($this->name){
            $this->name = DeCode::decode($this->name);
        }else{
            $this->name = explode('@',$this->email)[0]??'';
        }

    }

    /**
     * 匹配邮箱
     * @param $str
     * @return string
     * @author:dc
     * @time 2024/9/11 11:43
     */
    private function pregEmail(string $str):string {
        preg_match('/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/',$str,$email);
        if(empty($email[0])){
            // 邮箱2
            preg_match('/[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/',$str,$email);
        }
        return str_replace(['<','>'],'',$email[0]??'');
    }


    /**
     * @return string
     */
    public function getRaw(): string
    {
        return $this->raw;
    }

}