<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件


function pre($content, $is_die = true)
{
    header('Content-type: text/html; charset=utf-8');
    echo '<pre>' . print_r($content, true);
    $is_die && die();
}

/**
 * 异常处理函数
 * @param string $code
 * @param string $msg
 */
function json_error_exception($code = '', $msg = '')
{
    $error = config('errorCode.');
    $errorCode = isset($error[$code]) ? $code : 10000;
    $errorMsg = $msg != '' ? (isset($error[$code]) ? $error[$code] . " :" . $msg : $msg) : (isset($error[$code]) ? $error[$code] : "请求错误");
    return array('code' => $errorCode, 'msg' => $errorMsg);
}



/**
 * 成功Json返回函数
 * @param string $code
 * @param array  $data
 * @param string $msg
 */
function json_return($code,$data=[],$msg='')
{
    exit(json_encode(['code'=>$code,'data'=>$data,'msg'=>$msg],JSON_UNESCAPED_UNICODE ));
}

function json_success($data=[],$msg='ok')
{
    json_return(0, $data, $msg);
}

function json_error($code,$msg='')
{
    $error = json_error_exception($code,$msg);
    json_return($error['code'],[],$error['msg']);
}

function http_get($url,$data)
{
    return json_decode(http_request('GET',$url,$data),true);
}

function http_post($url,$data)
{
    return json_decode(http_request('POST',$url,$data),true);
}

function http_request($method,$url,$data)
{
    $method = strtolower($method);
    $params['method'] = $method;
    $params['url'] = $url;
    $params['data'] = $data;

    return _curl($params);
}

/**
 * php发送http请求
 * @param array $params 相关请求参数
 * @param booble $is_json  数据格式，默认false为数组，true为json
 * @return string
 */
function _curl(array $params,$is_json=false )
{
    $_data = $params['data'] ?? null;
    $url = $params['url'];
    $defaults = [
        CURLOPT_HEADER => 0,
        CURLOPT_URL => $params['url'],
        CURLOPT_FRESH_CONNECT => 1,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_FORBID_REUSE => 1,
        CURLOPT_TIMEOUT => 60,
        CURLOPT_SSL_VERIFYHOST=>2,
        CURLOPT_SSL_VERIFYPEER=>0,


    ];
    switch ($params['method'])
    {
        case 'post':
            $defaults[CURLOPT_CUSTOMREQUEST] = "POST";
            break;
        case 'get':
            $defaults[CURLOPT_CUSTOMREQUEST] = "GET";
            break;
        case 'put':
            $defaults[CURLOPT_CUSTOMREQUEST] = "PUT";
            break;
        case 'delete':
            $defaults[CURLOPT_CUSTOMREQUEST] = "DELETE";
            break;
    }
    if ($_data && $params['method']!='get') {
        if($is_json){
            $defaults[CURLOPT_POSTFIELDS] = json_encode($_data);
            $defaults[CURLOPT_HTTPHEADER] = [
                'Content-Type: application/json',
                'Content-Length: ' . strlen(json_encode($_data))
            ];
        }else{
            $defaults[CURLOPT_POSTFIELDS] = $_data;
        }
    }elseif($params['method']=='get'){
        if(is_array($_data)){
            $param = '';
            foreach ($_data as $k=>$v){
                $param .= $k."=".$v."&";
            }
            $param = rtrim($param ,"&");
            if(!strpos($url,"?")){
                $url .= "?".$param;
            }else{
                $url .= "&".$param;
            }
        }
        $defaults[CURLOPT_URL] = $url;
    }


    $ch = curl_init();
    curl_setopt_array($ch, ($defaults));

    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
}

function request_post($url = '', $postData = []) {
    if (empty($url)) {
        return false;
    }
    $postUrl = $url;
    //初始化curl //转义
    $ch = curl_init();
    if ($postData != []) {
        $vars = http_build_query($postData, '', '&');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
    }
    //抓取指定网页
    curl_setopt($ch, CURLOPT_URL,$postUrl);
    //设置header
    curl_setopt($ch, CURLOPT_HEADER, 0);
    //要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //规避SSL验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //跳过HOST验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    //运行curl
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

function http_post_json($url, $jsonStr)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($jsonStr)
        )
    );
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $response;
}
/**
 * 统一返回信息
 * @param $code
 * @param $data
 * @param $msge
 */
function msg($code, $data, $msg)
{
    return compact('code', 'data', 'msg');
}
/**
 * 对象转换成数组
 * @param $obj
 */
function objToArray($obj)
{
    return json_decode(json_encode($obj), true);
}