<?php
/**
 * 公共方法
 */

namespace Gm\Comm;

trait CommFunc {

    // 判断是否是get请求
    public function IsGet() {
        return $_SERVER['REQUEST_METHOD'] === 'GET' ? true : false;
    }

    // 通用返回错误信息
    public function ReturnErr($code = 500, $message = '操作失败') {
        $res = [
            'code' => $code,
            'message' => $message,
        ];
        echo json_encode($res);
    }

    // 通用返回正确信息
    public function ReturnSucc($code = 200, $message = '操作成功', $data = []): void
    {
        $res = [
            'code' => $code,
            'message' => $message,
            'data' => $data
        ];
        echo json_encode($res);
    }

    // 写入日志到文件
    public function logWriteFile($fileName, $content) {
        $fileName = $fileName. ".txt";
        file_put_contents("run/log/$fileName", json_encode($content), FILE_APPEND);
    }

    // get请求服务器
    public function REQUEST_URL_GET($url) {
        return file_get_contents($url);
    }


    // post请求服务器
    public function REQUEST_URL_POST($url, $data) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);

        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    // 生成uuid
    public function getUID(): int {
        return uniqid('', true);
    }
}


