<?php


namespace Api\PhpServices\XhProfiler;


class Xhprof
{
    public static $xhprof_service;
    private static $flag = false;

    protected function __construct()
    {

    }

    /**
     * 开启 xhprof 性能检测分析
     */
    public static function  getInstance()
    {
        if (empty(self::$xhprof_service))
        {
            return new XhProfilerService();
        }

        return false;
    }

    public static function startXhprof()
    {
        //从 yaconf 获取配置 ，判断当前域名是否要开启
        $config = \Yaconf::get('xhprof') ?? [];
        if (!self::judgeSwitch($config)) {
            return false;
        }
        self::$flag = true;

        self::$xhprof_service = self::getInstance();
        if ( !empty(self::$xhprof_service))
        {
            self::$xhprof_service->start();
        }
        return true;
    }

    /**
     * 开关决策器
     * @return bool
     */
    private static function judgeSwitch($config=[])
    {
        $domain = str_replace('.', '_',$_SERVER['SERVER_NAME']);
        $switch = $config['common']['switch'] ?? [];
        if (!isset($switch[$domain]) || random_int(0,100) >= $switch[$domain]) {
            return false;
        }

        return true;
    }

    /**
     * 关闭分析器，并且将数据写入mongo
     */
    public static function endXhprof()
    {
        if (!self::$flag) {
            return false;
        }

        self::$xhprof_service->end($_SERVER['SERVER_NAME']);
    }
}