<?php

/**
 * 加解密协议
 * Class Protocols
 */
class ProtocolsEvent
{
    /**
     * Notes:加密输出
     * User: wsc
     * Time: 2019/12/28 10:37
     * @param $str
     * @return string
     */
    public static function encode($str){
        $str = base64_encode($str);
        $key = floor(strlen($str)/2)-1;
        $out = substr($str,0,$key).substr(md5(time()),0,16).substr($str,$key,strlen($str));
        $out = substr($out,0,1).substr(md5(time()),0,1).substr($out,1,strlen($out));
        return $out;
    }
    /**
     * Notes:解码输出
     * User: wsc
     * Time: 2019/12/28 10:38
     * @param $str
     * @return bool|string
     */
    private static function decode($str){
        $str  = str_replace(" ","+",$str);
        $sign = substr($str,0,1).substr($str,2,strlen($str));
        $sign = substr($sign,0,floor((strlen($sign)-16)/2)-1).substr($sign,floor((strlen($sign)-16)/2)+15,strlen($sign));
        $sign = base64_decode($sign);
        return $sign;
    }

    /**
     * Notes:api接口输出封装
     * User: wsc
     * Time: 2019/12/28 10:49
     * @param $str
     */
    public static function apiEncode($str){

    }

    /**
     * Notes:api接口解码
     * User: wsc
     * Time: 2019/12/28 10:42
     * @param $str
     */
    public static function apiDecode($str){
        $sign = self::decode($str);
        $sign = trim($sign,'&');
        $sign = explode('&',$sign);
        foreach ($sign as $row){
            $temp = explode('=',$row,2);
            $_REQUEST[$temp[0]] = $temp[1];
            $_POST[$temp[0]] = $temp[1];
            $_GET[$temp[0]] = $temp[1];
        }
        unset($_REQUEST['param']);
        unset($_POST['param']);
        unset($_GET['param']);
    }
    /**
     * Notes:新api接口解码
     * User: wsc
     * Time: 2019/12/28 10:42
     * @param $str
     */
    public static function apiDecodeNew($str){
        $getParams = [];
        $sign = self::decode($str);
        $sign = trim($sign,'&');
        $sign = explode('&',$sign);
        foreach ($sign as $row){
            $temp = explode('=',$row,2);
            $getParams[$temp[0]] = $temp[1];
        }
        return $getParams;
    }
    /**
     * Notes:
     * User: wsc
     * Time: 2019/12/28 10:45
     * @param $str
     * @return bool|mixed|string
     */
    public static function wsDecode($str){
        $res = self::decode($str);
        $res = json_decode($res,true);
        return $res;
    }
}
