<?php
//  ---------------------------------------------------------------------------------
//    _____   _             _                   _   _____
//   |  __ \ | |           | |    /\           (_) |  __ \
//   | |__) || |__    __ _ | |   /  \    _ __   _  | |__) |_ __  ___
//   |  ___/ | '_ \  / _` || |  / /\ \  | '_ \ | | |  ___/| '__|/ _ \
//   | |     | | | || (_| || | / ____ \ | |_) || | | |    | |  | (_) |
//   |_|     |_| |_| \__,_||_|/_/    \_\| .__/ |_| |_|    |_|   \___/
//                                      | |
//                                      |_|
//   PhalApi Pro 专业版
//   广州果创网络科技有限公司
//
//  ---------------------------------------------------------------------------------
//
//   一、协议的许可和权利
//    1. 您可以在完全遵守本协议的基础上，将本软件应用于商业用途；
//    2. 您可以在协议规定的约束和限制范围内修改本产品源代码或界面风格以适应您的要求；
//    3. 您拥有使用本产品中的全部内容资料、商品信息及其他信息的所有权，并独立承担与其内容相关的
//       法律义务；
//    4. 获得商业授权之后，您可以将本软件应用于商业用途，自授权时刻起，在技术支持期限内拥有通过
//       指定的方式获得指定范围内的技术支持服务；
//
//   二、协议的约束和限制
//    1. 未获商业授权之前，禁止将本软件用于商业用途（包括但不限于企业法人经营的产品、经营性产品
//       以及以盈利为目的或实现盈利产品）；
//    2. 未获商业授权之前，禁止在本产品的整体或在任何部分基础上发展任何派生版本、修改版本或第三
//       方版本用于重新开发；
//    3. 如果您未能遵守本协议的条款，您的授权将被终止，所被许可的权利将被收回并承担相应法律责任；
//
//   三、有限担保和免责声明
//    1. 本软件及所附带的文件是作为不提供任何明确的或隐含的赔偿或担保的形式提供的；
//    2. 用户出于自愿而使用本软件，您必须了解使用本软件的风险，在尚未获得商业授权之前，我们不承
//       诺提供任何形式的技术支持、使用担保，也不承担任何因使用本软件而产生问题的相关责任；
//    3. 广州果创网络科技有限公司不对使用本产品构建的商城中的内容信息承担责任，但在不侵犯用户隐
//       私信息的前提下，保留以任何方式获取用户信息及商品信息的权利；
//
//   有关本产品最终用户授权协议、商业授权与技术服务的详细内容，均由广州果创网络科技有限公司独家
//   提供。广州果创网络科技有限公司拥有在不事先通知的情况下，修改授权协议的权力，修改后的协议对
//   改变之日起的新授权用户生效。电子文本形式的授权协议如同双方书面签署的协议一样，具有完全的和
//   等同的法律效力。您一旦开始修改、安装或使用本产品，即被视为完全理解并接受本协议的各项条款，
//   在享有上述条款授予的权力的同时，受到相关的约束和限制。协议许可范围以外的行为，将直接违反本
//   授权协议并构成侵权，我们有权随时终止授权，责令停止损害，并保留追究相关责任的权力。
//
//  ---------------------------------------------------------------------------------

namespace Admin\Api;

use Admin\Common\Api;
use Base\Domain\ApiDesign as ApiDesignDomain;
use Base\Model\ApiDesign as ApiDesignModel;


/**
 * 接口设计模块
 */
class ApiDesign extends Api {

    public function getRules() {
        $requestJson = '所有的参数传递json字符串，
                        <br>请求的参数key分别对应：name:参数名称(英文), type:类型, desc:参数说明, require:必须(true或者false), default:默认值, max:最大值, min:最小值。当为空时填null。
                        <br>示例: [{"name":"yesapi","type":"string","require":true,"default":"phalapi","min":1,"max":100,"desc":"描述"},{"name":"age","type":"int","require":false,"default":"1","min":0,"max":100,"desc":"年龄"}]
                        <br>更多详细规则参考：<a href="http://docs.phalapi.net/#/v2.0/api-params" target="_blank">接口参数规则</a>';
        $responseJson = '所有的参数传递json字符串，请求的参数key分别对应：<br>
                        name:返回字段名称(英文), type:返回字段类型, desc:返回字段说明。 type的值可能为string，int，float，bool，array，object，date
                        示例: [{"name":"yesapi","type":"string","desc":"描述"},{"name":"age","type":"int","desc":"年龄"}]';
        return array(
            'addApiDesign' => array(
                'apiName' => array('name' => 'api_name', 'require' => true, 'max' => 100, 'desc' => '接口服务名称，必须以App开头'),
                'apiModules' => array('name' => 'api_modules', 'type' => 'string', 'require' => true, 'desc' => '接口模块名称'),
                'apiTitle' => array('name' => 'api_title', 'type' => 'string', 'require' => true, 'desc' => '接口服务名称'),
                'apiDesc' => array('name' => 'api_desc', 'type' => 'string', 'require' => true, 'desc' => '接口服务描述'),
                'apiRequestParams' => array('name' => 'api_request_params', 'type' => 'string',  'desc' => '接口请求参数规则：'.$requestJson),
                'apiResponseParams' => array('name' => 'api_response_params', 'type' => 'string',  'desc' => '接口返回参数规则：'.$responseJson),
                'apiResponseExample' => array('name' => 'api_response_example', 'type' => 'string', 'desc' => '接口返回示例(json)'),
            ),
            'getDraft' => array(),
            'createCodeTemplate' => array(
                'apiName' => array('name' => 'api_name', 'max' => 100, 'desc' => '接口服务名称，必须以App开头'),
                'apiModules' => array('name' => 'api_modules', 'type' => 'string', 'desc' => '接口模块名称'),
                'apiTitle' => array('name' => 'api_title', 'type' => 'string', 'desc' => '接口服务名称'),
                'apiDesc' => array('name' => 'api_desc', 'type' => 'string', 'desc' => '接口服务描述'),
                'apiRequestParams' => array('name' => 'api_request_params', 'type' => 'string', 'desc' => '接口请求参数'.$requestJson),
                'apiResponseParams' => array('name' => 'api_response_params', 'type' => 'string', 'desc' => '接口返回参数'.$responseJson),
                'isDataApi' => array('name' => 'is_data_api', 'type' => 'int', 'default' => 1, 'desc' => '是否生成数据接口API，同时创建数据库表，1是0否'),
            ),
            'updateApiDesign' => array(
                'id' => array('name' => 'id', 'type' => 'int', 'require' => true, 'desc' => '要更新的id'),
                'apiName' => array('name' => 'api_name', 'max' => 100, 'desc' => '接口服务名称，必须以App开头'),
                'apiModules' => array('name' => 'api_modules', 'type' => 'string', 'desc' => '接口模块名称'),
                'apiTitle' => array('name' => 'api_title', 'type' => 'string', 'desc' => '接口服务名称'),
                'apiDesc' => array('name' => 'api_desc', 'type' => 'string',  'desc' => '接口服务描述'),
                'apiRequestParams' => array('name' => 'api_request_params', 'type' => 'string', 'desc' => '接口请求参数'. $requestJson),
                'apiResponseParams' => array('name' => 'api_response_params', 'type' => 'string', 'desc' => '接口返回参数'. $responseJson),
                'apiResponseExample' => array('name' => 'api_response_example', 'type' => 'string',  'desc' => '接口返回示例(json)'),
            ),
            'saveAndCreateApi' => array(
                'id' => array('name' => 'id', 'type' => 'int', 'require' => true, 'desc' => '要生成的接口设计id'),
                'isForce' => array('name' => 'is_force', 'type' => 'int', 'default' => 1, 'desc' => '文件存在是否强制覆盖，1表示不覆盖，2表示覆盖'),
                'isDataApi' => array('name' => 'is_data_api', 'type' => 'int', 'default' => 1, 'desc' => '是否生成数据接口API，同时创建数据库表，1是0否'),
            ),
            'delApiDesign' => array(
                'id' => array('name' => 'id', 'type' => 'int', 'require' => true, 'desc' => '要删除的id'),
            )
        );   
    }

    /**
     * 添加接口设计
     * @desc 添加接口设计
     * @return bool     code      是否添加成功，true表示添加成功，false添加失败
     * @return string   msg       添加成功失败信息
     * @return int      id        添加成功的id
     * @return string   addTime   添加时间
     */
    public function addApiDesign(){
        $rs = array('code' => true, 'msg' => '添加成功', 'id' => 0);
        if (!$this->checkApiName($this->apiName)){
            $rs['code'] = false;
            $rs['msg'] = \PhalApi\T('wrong service name');
            return $rs;
        }
        if (!$this->checkApiRequestParams($this->apiRequestParams)){
            $rs['code'] = false;
            $rs['msg'] = \PhalApi\T('wrong API params config');
            return $rs;
        }
        if (!$this->checkApiResponseParams($this->apiResponseParams)){
            $rs['code'] = false;
            $rs['msg'] = \PhalApi\T('wrong API response config');
            return $rs;
        }
//        if (!$this->checkApiResponseExample($this->apiResponseExample)){
//            $rs['code'] = false;
//            $rs['msg'] = '接口返回示例有误，请传递json字符串';
//            return $rs;
//        }
        $this->apiName = ucfirst($this->apiName);
        
        $model = new ApiDesignModel;
        $rs['id'] = $model->insert(
            array(
                'uid' => \PhalApi\DI()->context->getUid(),
                'api_name' => $this->apiName, 'api_modules' => $this->apiModules,
                'api_title' => $this->apiTitle, 'api_desc' => $this->apiDesc,
                'api_request_params' => is_null($this->apiRequestParams) ? "[]" : $this->apiRequestParams,
                'api_response_params' => is_null($this->apiResponseParams) ? "[]" : $this->apiResponseParams,
                'api_response_example' => is_null($this->apiResponseExample) ? "[]" : $this->apiResponseExample,
                'add_time' => date("Y-m-d H:i:s"),
            )
        );
        $rs['addTime'] = date("Y-m-d H:i:s");
        return $rs;
    }

    /**
     * 获取草稿接口设计
     * @desc 获取是否有草稿的接口设计
     * @return bool   has_draft 是否有草稿，true表示有，false无
     * @return array  draft     接口设计草稿
     */
    public function getDraft(){
        $rs = array('has_draft' => false, 'draft' => array());
        $uid = \PhalApi\DI()->context->getUid();
        $domain = new ApiDesignDomain;
        $apiDesignData = $domain->getDraft($uid);
        if(!empty($apiDesignData)){
            $rs['has_draft'] = true;
            $rs['draft'] =$apiDesignData;
        }
        return $rs;
    }

    /**
     * 更新接口设计
     * @desc 更新接口设计
     * @return bool   isUpdate  是否更新成功，true表示更新成功，false无更新
     * @return string msg       更新信息
     * @return string time      更新时间
     */
    public function updateApiDesign(){
        $rs = array('isUpdate' => false, 'msg' => \PhalApi\T('no data updated'));
        if (!$this->checkApiName($this->apiName)){
            $rs['msg'] = \PhalApi\T('wrong service name');
            return $rs;
        }
        if (!$this->checkApiRequestParams($this->apiRequestParams)){
            $rs['msg'] = \PhalApi\T('wrong API params config');
            return $rs;
        }
        if (!$this->checkApiResponseParams($this->apiResponseParams)){
            $rs['msg'] = \PhalApi\T('wrong API response config');
            return $rs;
        }
//        if (!$this->checkApiResponseExample($this->apiResponseExample)){
//            $rs['msg'] = '接口返回示例有误，请传递json字符串';
//            return $rs;
//        }
        
        $this->apiName = ucfirst($this->apiName);
        
        $domain = new ApiDesignDomain();
        $updateRows = $domain->updateApiDesign($this->id, $this->apiName, $this->apiModules, $this->apiTitle,
            $this->apiDesc, $this->apiRequestParams, $this->apiResponseParams, $this->apiResponseExample);
        if($updateRows > 0) {
            $rs['isUpdate'] = true;
            $rs['msg'] = \PhalApi\T('update successfully');
        }
        $rs['time'] = date("Y-m-d H:i:s");
        return $rs;
    }

    /**
     * 生成代码接口
     * @desc 根据传参，生成对应的代码骨架
     * @return string code 生成的php代码
     * @return string path 生成的代码路径
     */
    public function createCodeTemplate()
    {
        $this->apiName = ucfirst($this->apiName);
        
        $template = $this->createCode($this->apiName, $this->apiModules, $this->apiTitle, $this->apiDesc, $this->apiRequestParams, $this->apiResponseParams, $this->isDataApi);
        $path =  substr(API_ROOT, 0, strlen(API_ROOT)-10)."/src/app/Api/{类名}.php";
        if ($this->apiName != null){
            $apiArr = explode('.', $this->apiName);
            $path = str_replace("{类名}", $apiArr[1],$path);
        }
        return array('code' => $template, 'path' => $path);
    }

    /**
     * 保存生成代码文件
     * @desc 根据传参，生成代码文件
     * @return bool   isCreate   是否创建成功，true表示创建成功，false表示创建失败
     * @return string msg        创建信息
     * @return string exampleMsg 创建示例信息
     * @return string docs       接口文档地址
     * @return string isExists   接口文件是否存在
     * @return bool isCreateExample 接口示例是否创建成功
     */
    public function saveAndCreateApi(){
        $rs = array('isCreate' => false, 'msg' => \PhalApi\T('fail to generate code'), 'exampleMsg' => \PhalApi\T('fail to generate demo file'), 'docs' => $_SERVER['HTTP_HOST']."/docs.php", 'isExists' => false, 'isCreateExample' => false);

        // 保存代码
        $domain = new ApiDesignDomain();
        $domain->saveApiDesign($this->id);

        $apiData = $domain->getApiData($this->id);
        // 获取生成代码
        $code = $this->createCode($apiData['api_name'], $apiData['api_modules'], $apiData['api_title'], $apiData['api_desc'], $apiData['api_request_params'], $apiData['api_response_params'], $this->isDataApi);
        $nameArr = explode('.', $apiData['api_name']);
        if(empty($nameArr) || empty($nameArr[1])){
            $rs['msg'] = \PhalApi\T("wrong config");
            return $rs;
        }
        $module = $nameArr[1];
        $dirPath = API_ROOT.'/src/app/Api';
        $filePath = API_ROOT.'/src/app/Api/'.$module.'.php';

        if (file_exists($filePath)){
            if($this->isForce == 1){
                $rs['msg'] = \PhalApi\T('file exists');
                $rs['isExists'] = true;
                return $rs;
            }else{
                $handle = fopen($filePath,'w');
                $res = fwrite($handle, $code);
                if ($res !== false){
                    $rs['isCreate'] = true;
                    $rs['msg'] = \PhalApi\T("succeed to generate code");
                }
                fclose($handle);
            }
        } else if (!is_writable($dirPath)){
            $rs['msg'] = \PhalApi\T("no write permission");
            return $rs;
        }else{
            $handle = fopen($filePath,'w+');
            $res = fwrite($handle, $code);
            if ($res !== false){
                $rs['isCreate'] = true;
                $rs['msg'] = \PhalApi\T("succeed to generate code");
                $rs['docs'] = $_SERVER['HTTP_HOST']."/docs.php?service=" . $apiData['api_name'] . "&detail=1&type=fold";
            }
            fclose($handle);
        }
        
        // 数据接口
        if ($this->isDataApi == 1) {
            $modelCode = $this->createModelCode($module);
            $modelFile = API_ROOT.'/src/app/Model/'.$module.'.php';
            if (!file_exists($modelFile)) {
                file_put_contents($modelFile, $modelCode);
            }
            
            try {
                $modelSql = $this->createModelSql($module, $apiData['api_request_params']);
                \PhalApi\DI()->notorm->test->executeSql($modelSql, array());
            } catch (\PDOException $ex) {
                // ignore
            }
        }

        // 添加示例
        $examplePath = API_ROOT.'/src/view/docs/demos';
        $exampleFile = API_ROOT.'/src/view/docs/demos/' . $apiData['api_name'].'.json';
        if (!is_writable($examplePath)){
            $rs['exampleMsg'] = \PhalApi\T('no write permission：src/view/docs/demos');
            return $rs;
        }
        $handle2 = fopen($exampleFile,'w+');
        if(fwrite($handle2, $apiData['api_response_example']) !== false){
            $rs['isCreateExample'] = true;
            $rs['exampleMsg'] = \PhalApi\T("succeed to generate demo file");
        }
        fclose($handle2);
        $rs['docs'] = $_SERVER['HTTP_HOST']."/docs.php?service=" . $apiData['api_name'] . "&detail=1&type=fold";
        return $rs;
    }

    /**
     * 删除接口设计
     * @desc 删除接口设计
     * @return bool     code 删除是否成功
     * @return string   msg  删除信息
     */
    public function delApiDesign(){
        $rs = array('code' => false, 'msg' => \PhalApi\T('fail to delete'));
        $model = new ApiDesignModel();
        if($model->delete($this->id)){
            $rs['code'] = true;
            $rs['msg'] = \PhalApi\T("succeed to delete");
        }
        return $rs;
    }

    protected function checkApiName($apiName){
        $nameArr = explode('.', $apiName);
        if (count($nameArr) == 3 && $nameArr[0] == 'App') {
            return true;
        }
        return false;
    }

    protected function checkApiRequestParams($apiRequestParams){
        if($apiRequestParams !== null){
            $arr = $this->checkIsJson($apiRequestParams);
            if (empty($arr)){
                return false;
            }
            // 检查参数
            $keyList = array('name', 'type', 'desc', 'require', 'default', 'max', 'min');
            foreach ($arr as $item){
                foreach ($item as $key => $_){
                    if(!in_array($key, $keyList)){
                        return false;
                    }
                }
            }
            return true;
        }
        return true;
    }

    protected function checkApiResponseParams($apiResponseParams){
        if ($apiResponseParams !== null){
            $arr = $this->checkIsJson($apiResponseParams);
            if (empty($arr)){
                return false;
            }
            // 检查参数
            $keyList = array('name', 'type', 'desc');
            foreach ($arr as $item){
                foreach ($item as $key => $_){
                    if(!in_array($key, $keyList)){
                        return false;
                    }
                }
            }
            return true;
        }
        return true;
    }

    protected function checkApiResponseExample($apiResponseExample){
        if($apiResponseExample !== null){
            $arr = $this->checkIsJson($apiResponseExample);
            return empty($arr) ? false : true;
        }
        return true;
    }

    protected function checkIsJson($paramStr){
        $jsonArr = json_decode($paramStr, true);
        if(is_null($jsonArr)){
            return array();
        }
        return $jsonArr;
    }

    //    生成参数规则
    //  'apiName' => array('name' => 'api_name', 'require' => true, 'max' => 100, 'desc' => '接口服务名称，必须以App开头'),
    protected function createRequestParams($apiRequestParams){
        $arr = $this->checkIsJson($apiRequestParams);
        // 转为map
        $map = array();
        foreach ($arr as &$item){
            $name = $item['name'];
            foreach ($item as $k => $v){
                if(empty($v)){
                    unset($item[$k]);
                }else{
                    if(in_array($k, array('min', 'max', 'default'))){
                        if($item['type'] == 'int'){
                            $item[$k] = intval($v);
                        }elseif ($item['type'] == 'float'){
                            $item[$k] = floatval($v);
                        }
                    }
                }
            }
            $map[$name] = $item;
            unset($item);
        }
        $code = "";
        foreach ($map as $key => $ruleList){
            $code .= "
                '$key' => ". str_replace("\n", "\n              ", var_export($ruleList, true)).",\n";
        }
        return $code;
    }

    // 生成返回参数
    // @return bool   has_draft 是否有草稿，true表示有，false无
    protected function createReturnString($apiResponseParams){
        $arr = $this->checkIsJson($apiResponseParams);
        $code = "";
        foreach ($arr as $item){
            if (!isset($item['type'])) {
                $item['type'] = 'string';
            }
            $code .= "     * @return {$item['type']} {$item['name']}  {$item['desc']}\n";
        }
        return $code;
    }

    // 生成代码
    protected function createCode($apiName, $apiModules, $apiTitle, $apiDesc, $apiRequestParams, $apiResponseParams, $isDataApi = 0){
        $baseApi = $isDataApi == 1 ? 'use App\Common\DataApi as Api;' : 'use App\Common\Api;';
        
        $template = "<?php
namespace App\Api;
{$baseApi}
// use App\Domain\{接口类名} as {接口类名}Domain;

/**
 * {接口模块名称}
 */
class {接口类名} extends Api {

    /**
     * 接口参数规则配置
     */
    public function getRules() {
        \$rules = parent::getRules();
        \$curRules = array(
            '{接口方法名}' => array(
                {参数规则}
            ),
        );
        return array_merge(\$rules, \$curRules);
    }

    /**
     * {接口标题}
     * @desc {接口描述}
{返回结果注释}
     */ 
    public function {接口方法名}() {
        // 接口参数获取
        {接口参数获取}
        // 获取用户ID，未登录时异常返回
        // \$uid = \$this->tryToGetUid();

        // 获取app_key，未指定时异常返回
        // \$appKey = \$this->tryToGetAppKey();

        // TODO: 实现你的业务逻辑……
        // \$domain = new {接口类名}Domain();

        // 结果返回
        {返回参数}
        return \$rs;

    }

    // 绑定数据库模型
    protected function getDataModel() {
        return new \App\Model\{接口类名}();
    }
}";
        if (!empty($apiModules)) {
            $template = str_replace("{接口模块名称}", $apiModules, $template);
        }

        if(!empty($apiRequestParams) && $this->checkApiRequestParams($apiRequestParams)){
            $template = str_replace("{参数规则}", $this->createRequestParams($apiRequestParams) , $template);
            // 获取接口参数
            $arr = $this->checkIsJson($apiRequestParams);
            $params = "";
            foreach ($arr as $item){
                $name = $item['name'];
                $params .= "\$$name = \$this->$name;\n        ";
            }
            $template = str_replace("{接口参数获取}", $params, $template);
        }else{
            $template = str_replace("{参数规则}", "// ", $template);
            $template = str_replace("{接口参数获取}", "// 接口参数获取", $template);
        }

        if (!empty($apiTitle)) {
            $template = str_replace("{接口标题}", $apiTitle, $template);
        }

        if (!empty($apiDesc)) {
            $template = str_replace("{接口描述}", $apiDesc, $template);
        }

        if (!empty($apiName)) {
            $apiArr = explode('.', $apiName);
            $template = str_replace("{接口类名}", $apiArr[1], $template);
            $template = str_replace("{接口方法名}", $apiArr[2], $template);
        }

        if(!empty($apiResponseParams) && $this->checkApiResponseParams($apiResponseParams)){
            $template = str_replace("{返回结果注释}",
                $this->createReturnString($apiResponseParams)
                ,$template);

            $template = str_replace("{返回参数}", $this->createDefaultResponse($apiResponseParams), $template);
        }else{
            $template = str_replace("{返回结果注释}", "", $template);
            $template = str_replace("{返回参数}", "\$rs =array(); \n", $template);
        }
        return $template;
    }

    protected function createModelCode($modelName) {
        $template = "<?php
namespace App\Model;
use PhalApi\Model\DataModel;

// 可以考虑将此类移到base/src/Model目录下
class {$modelName} extends DataModel {
    public function getTableName(\$id) {
        return '{$modelName}';
    }
}";
        return $template;
    }
    
    protected function createModelSql($modelName, $apiRequestParams) {
        $fieldsSql = '';
        if($apiRequestParams !== null){
            $arr = $this->checkIsJson($apiRequestParams);
            foreach ($arr as $item){
                $name = $item['name'];
                $type = isset($item['type']) ? $item['type'] : 'string';
                $sqltype = $type == 'int' ? 'int(11)' : 'varchar(1000)';
                $default = isset($item['default']) ? $item['default'] : null;
                $sqldefault = $type == 'int' ? intval($default) : addslashes(strval($default));
                $desc = isset($item['desc']) ? addslashes($item['desc']) : '';
                
                $fieldsSql .= "`{$name}` {$sqltype} DEFAULT '{$sqldefault}' COMMENT '{$desc}',";
            }
        }
        
        $prefix = \PhalApi\DI()->config->get('dbs.tables.__default__.prefix');
        $sql = "CREATE TABLE `{$prefix}{$modelName}` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
$fieldsSql
  `uid` int(11) DEFAULT '0' COMMENT 'user表的用户ID',
  `app_key` varchar(100) NOT NULL DEFAULT '' COMMENT 'app_key，客户端key',
  `add_time` datetime COMMENT '创建时间',
  `update_time` datetime COMMENT '最后更新时间',
  PRIMARY KEY (`id`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;";
        return $sql;
    }
    
    protected function createDefaultResponse($apiResponseParams){
        $code = "\$rs = array(";
        $arr = $this->checkIsJson($apiResponseParams);
        foreach ($arr as $item){
            $name = $item['name'];
            $type = $item['type'];
            switch ($type){
                case "string":
                    $defaultValue = '""'; break;
                case "int":
                    $defaultValue = 0;  break;
                case "float":
                    $defaultValue = 0.0;    break;
                case "bool":
                    $defaultValue = "true";   break;
                case "date":
                    $defaultValue = '"'.date("Y-m-d H:i:s").'"'; break;
                case "array":
                    $defaultValue = "array()";    break;
                default:
                    $defaultValue = 'null';   break;
            }
            $code .= "'$name' => $defaultValue,";
        }
        $code .= "); \n";
        return $code;
    }

}
