<?php

namespace Lib;


/**
 * 日志文件
 * @author:dc
 * @time 2023/3/14 10:26
 * Class Log
 * @package Lib
 */
class Log {


    /**
     * @var array
     */
    protected array $filename = [];

    /**
     * @var array
     */
    protected array $message = [];

    /**
     * @var self
     */
    private static self $instance;

    /**
     * Log constructor.
     */
    public function __construct()
    {

    }

    /**
     * 追加日志内容
     * @param string $message
     * @param null $filename
     * @return Log
     * @author:dc
     * @time 2024/7/18 14:12
     */
    public static function append(string $message, $filename = null){

        if($filename){
            self::getInstance()->setFilename($filename);
        }

        self::getInstance()->message[$filename ? md5($filename) : 'default'][] = date('Y-m-d H:i:s  ').$message;
        return self::getInstance();
    }


    /**
     * @return Log
     */
    public static function getInstance(): Log
    {
        if (empty(static::$instance)){
            static::$instance = new Log();
        }

        return self::$instance;
    }

    /**
     * 设置日志文件
     * @param $filename
     * @author:dc
     * @time 2023/3/14 11:11
     */
    private function setFilename($filename){
        $this->filename[md5($filename)] = $filename;

        // 创建目录
        if(!is_dir(dirname($filename))){
            @mkdir(dirname($filename),0755,true);
        }

    }

    /**
     * @return array
     */
    protected function getFilename($key=null): string
    {
        return $this->filename[$key]??LOG_PATH.'/'.date('Y-m-d').'.error.log';
    }

    /**
     * 写入日志
     * @author:dc
     * @time 2023/3/14 10:45
     */
    public function write(){

        foreach ($this->message as $key=>$msg){

            $fo = @fopen($this->getFilename($key),'a');
            if(!$fo){
                $fo = @fopen($this->getFilename(),'a');
            }
            if($fo){
                foreach ($msg as $log){
                    @fwrite($fo,$log.PHP_EOL);
                }
                @fclose($fo);
            }

            $this->message[$key] = null;
            unset($this->message[$key]);

        }

    }

    /**
     * 立即写入文件
     * @param $filename
     * @param $data
     * @param null $flag
     * @author:dc
     * @time 2024/11/13 15:30
     */
    public static function put($filename,$data,$flag=null){
        if (!dirname($filename)){
            @mkdir(dirname($filename),0775,true);
        }
        @file_put_contents($filename,$data,$flag);
    }

    public function __destruct()
    {
        $this->write();
    }
}