ImapClient.php 2.7 KB
<?php

namespace Lib\Imap;

class ImapClient {

    /**
     * 资源
     * @var
     */
    private $socket;

    protected bool $debug = false;

    protected string $host;


    /**
     * 每请求一次就会+1
     * @var int
     */
    public int $tagNum = 0;

    public function __construct(string $host){
        $this->host = $host;
    }

    public function open(){
        $content = stream_context_create([
            'ssl' => [
                'verify_peer' => false, // 有的证书和域名不匹配,这里关闭认证
                'verify_peer_name' => false,// 有的证书和域名不匹配,这里关闭认证
            ]
        ]);

        $flags = STREAM_CLIENT_CONNECT;

        $this->socket = stream_socket_client(
            $this->host,
            $errno,
            $error,
            30,
            $flags,
            $content
        );

        if($error){
            throw new \Exception($error);
        }

        if (!$this->socket) {
            throw new \Exception($this->host." connection fail.");
        }
    }


    /**
     * @param bool $debug
     * @return $this
     * @author:dc
     * @time 2024/9/18 9:57
     */
    public function setDebug(bool $debug = true): static
    {
        $this->debug = $debug;
        return $this;
    }



    /**
     * 写
     * @param string $cmd
     * @return false|int
     * @author:dc
     * @time 2024/9/13 15:47
     */
    protected function write(string $cmd){
        if($this->debug){
            echo 'write: '.$cmd;
        }
        return fwrite($this->socket,$cmd);
    }

    /**
     * 读
     * @return false|string
     * @author:dc
     * @time 2024/9/13 15:49
     */
    protected function readLine(){
        $str = fgets($this->socket,2048);
        if($this->debug){
            echo 'read: '.$str;
        }
        return $str;
    }

    /**
     *
     * @param string $cmd 执行的命令
     * @return array
     * @author:dc
     * @time 2024/9/13 15:57
     */
    public function request(string $cmd):array {
        $this->tagNum++;
        $tag = 'TAG'.$this->tagNum;
        // 请求数据
        $writeNumber = $this->write($tag.' '.$cmd."\r\n");
        $result = [];
        if($writeNumber){
            // 读取数据
            while (1){
                $line = $this->readLine();
                $result[] = $line;
                list($token) = explode(' ',$line,2);
                // 结束了
                if($token == $tag || $line === false){
                    break;
                }
            }
        }

        return $result;

    }


    public function __destruct()
    {
        @fclose($this->socket);
        unset($this->socket);
        // TODO: Implement __destruct() method.
    }

}