<?php
// 分析文件写入文件夹
$xhprof_dir = "/data/log/xhprof";
// 存库后 移入的文件夹
$xhprof_new_dir = "/data/log/xhprofdb/";
// 数据库配置
$db_config = [
    'hostname' => '127.0.0.1',
    'username' => 'root',
    'password' => '(M12JI237^&1',
    'database' => 'game-tools',
    'port' => '3306',
];
// 后台配置的数据库表
$xhprof_set_tbl = 'xhprof_data';

// 得到文件信息 
$dir_list = list_file($xhprof_dir);

// 插入数据库
ins_db($dir_list, $xhprof_dir, $xhprof_new_dir, $db_config, $xhprof_set_tbl);

function ins_db($arr, $dir, $new_dir_back, $db_config, $tbl) {
    $mysql = new mysqli($db_config['hostname'], $db_config['username'], $db_config['password'], $db_config['database'], $db_config['port']);
    if($mysql->connect_errno) {
        dir($mysql->connect_error);
    }
    foreach($arr as $ins) {
        $file_dir = $dir. '/' . $ins;
        $new_dir = $new_dir_back . $ins;
        $ins_arr = explode('-', $ins);
        $uid    = '"'.$ins_arr[0].'"';
        $model  = '"'.$ins_arr[1].'"';
        $action = '"'.$ins_arr[2].'"';
        $unix   = '"'.$ins_arr[3].'"';
        $wt     = '"'.$ins_arr[4].'"';
        $cpu    = '"'.$ins_arr[5].'"';
        $mu     = '"'.$ins_arr[6].'"';
        $pmu    = '"'.$ins_arr[7].'"';
        $sql = "insert into $tbl (model,action,unix,wt,cpu,mu,uid,pmu) values($model,$action,$unix,$wt,$cpu,$mu, $uid,$pmu)";
        $mysql->query($sql);

        // 移动目录到另外一个目录
        rename($file_dir, $new_dir);
    }

    $mysql->close();
}

function list_file($dir){
    if (!is_dir($dir)) return false;
    $dir_list = [];
    $temp = scandir($dir);

    foreach($temp as $v) {
        $file_dir = $dir. '/' . $v;
        if (!is_dir($file_dir)) {
            $vArr = explode('-', $v);
            $dir_list[$vArr['3']] = $v;
        }
    }
    ksort($dir_list);
    array_shift($dir_list);

    return $dir_list;
}

