Folders.php 2.6 KB
<?php

namespace Lib\Imap\Parse\Folder;


/**
 * 文件夹
 * @author:dc
 * @time 2024/9/20 9:33
 * Class Folder
 * @package Lib\Imap\Parse
 */
class Folders{

    /**
     * @var Folder[]
     */
    protected array $item = [];


    /**
     * 原始头信息
     * @var string
     */
    protected array $raw = [];

    /**
     * Header constructor.
     * @param array $raw
     */
    public function __construct(array $raw)
    {
        $this->raw = $raw;

        $this->parse();
    }

    /**
     * 解析目录
     * @author:dc
     * @time 2024/9/20 10:07
     */
    private function parse(){
        foreach ($this->raw as $item){
            // 解析源数据
            if(preg_match('/^\*\sLIST\s\(([\\a-z\s]{0,})\)\s\"(.*)\"\s\"?(.*)\"?$/Ui',$item,$m)){
                if($m[1]){
                    $flags = explode(' ',$m[1]);
                    $flags = array_map(function ($v){
                        $v = trim($v);
                        $v = trim($v,'\\');
                        return $v;
                    },$flags);
                    $flags = array_filter($flags,function ($v){
                       return !empty($v);
                    });
                }else{
                    $flags = [];
                }


                $this->item[] = new Folder(trim(trim($m[3]),'"'),$flags, !str_contains($m[1], 'NoSelect'), $this);
            }
        }

    }

    /**
     * 获取顶级栏目 一级目录
     * @return Folder[]
     * @author:dc
     * @time 2024/9/20 11:39
     */
    public function getTopFolder():array {
        return array_filter($this->item,function ($folder){
            return substr_count($folder->folder,'/') == 0;
        });
    }


    /**
     * 查找当前目录的下级目录
     * @param Folder $folder
     * @return Folder[]
     * @author:dc
     * @time 2024/9/19 17:54
     */
    public function findChild(Folder $folder):array {
        $fs = [];
        foreach ($this->item as $item){
            // 跳过相同目录
            if($folder->folder == $item->folder) continue;
            if(strpos($item->folder,$folder->folder) !== 0) continue;

            $f = substr($item->folder,strlen($folder->folder),999);
            $f = ltrim($f,'/');
            if(substr_count($f,'/') == 0){
//                $item['child'] = $this->findChild($item['folder']);
                $fs[] = $item;
            }
        }
        return $fs;
    }


    /**
     * 获取所有目录 list 不是tree结构
     * @return Folder[]
     * @author:dc
     * @time 2024/9/20 11:43
     */
    public function all():array{
        return $this->item;
    }


}