<?php

namespace Api\PhpServices\XhProfiler;


use Xhgui\Profiler\Profiler;

class XhProfilerService
{
    private $profiler;

    public function __construct()
    {
        $this->profiler =  new Profiler([]);
    }

    /**
     * 开启 xhprofiler 分析
     */
    public function start(): void
    {
        //开启 分析器，并且初始化 mongodb 实例
        $this->profiler->start();
    }

    /**
     * 结束分析
     * @param $domain
     */
    public function end($domain): void
    {
        // 结束分析器，生产性能检测数据
        $profiler_data = $this->profiler->disable();
        $profiler_data = $this->dealProfile($profiler_data,$domain);

        $mongo = XhMongo::getInstance();
        $mongo->insertOne($profiler_data);

    }

    private function dealProfile(array $profile,$domain)
    {
        $profile['profile'] = $this->encodeProfile($profile['profile']);
        $profile['domain'] = str_replace('.', '_',$domain);
        return $profile;
    }

    private function encodeProfile(array $profile)
    {
        $results = array();
        foreach ($profile as $k => $v) {
            if (strpos($k, '.') !== false) {
                $k = str_replace('.', '_', $k);
            }
            $results[$k] = $v;
        }

        return $results;
    }

}