Address.php 2.5 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);
    }

    /**
     * 解析地址
     * 情况1  "name" <xxx@email.com>
     * 情况2  "name" xxx@email.com
     * 情况3  name xxx@email.com
     * 情况4  xxx@email.com
     * @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($this->raw);
            $len = strlen($email);

            if(substr($this->name,-1)=='>'){
                $len += 2;
            }

            $this->name = substr($this->name,0,-$len);
            $this->name = trim($this->name);
            $this->name = trim($this->name,'"');
        }
        if($this->name){
//            $this->name = DeCode::decode($this->name);
            $this->name = Header::mime_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_all('/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/',$str,$email);
        if(!empty($email[0])){
            $email = end($email[0]);
        }else{
            $email = '';
        }
        if(empty($email)){
            // 邮箱2
            preg_match_all('/[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/',$str,$email);

            if(!empty($email[0])){
                $email = end($email[0]);
            }else{
                $email = '';
            }
        }
        return str_replace(['<','>'],'',$email);
    }


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


    public function toArray():array {
        return [
            'email' =>  $this->email,
            'name'  =>  $this->name
        ];
    }

}