You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

293 lines
8.3 KiB

4 years ago
  1. <?php
  2. namespace Api\Controller;
  3. use Think\Controller;
  4. class ImportSwaggerController extends BaseController {
  5. public function import(){
  6. $login_user = $this->checkLogin();
  7. $json = file_get_contents($_FILES["file"]["tmp_name"]) ;
  8. //$json = file_get_contents("../Public/swagger.json") ;//test
  9. $json_array = json_decode($json ,1 );
  10. unset($json);
  11. if ($json_array['info']) {
  12. $this->_fromSwaggerV2($json_array);
  13. return ;
  14. }
  15. $this->sendError(10303);
  16. }
  17. private function _fromSwaggerV2($json_array){
  18. $login_user = $this->checkLogin();
  19. // TODO 这里需要检查下合法性。比如关键字检查/黑名单检查/字符串过滤
  20. $from = I("from") ? I("from") : '' ;
  21. $item_array = array(
  22. "item_name" => $json_array['info']['title'] ? $json_array['info']['title'] : 'from swagger' ,
  23. "item_type" => '1' ,
  24. "item_description" => $json_array['info']['description'] ? $json_array['info']['description'] :'',
  25. "password" => time().rand(),
  26. "members" => array(),
  27. "pages" =>array(
  28. "pages" => array(),
  29. "catalogs" => array(
  30. array(
  31. "cat_name" =>'from swagger',
  32. "pages" =>array()
  33. )
  34. )
  35. )
  36. ) ;
  37. $level = 2 ;
  38. $item_array['pages']['catalogs'][0]['pages'] = $this->_getPageByPaths($json_array);
  39. $item_id = D("Item")->import( json_encode($item_array) , $login_user['uid'] );
  40. //echo D("Item")->export(196053901215026 );
  41. //echo json_encode($item_array);
  42. $this->sendResult(array('item_id' => $item_id));
  43. }
  44. private function _getPageByPaths($json_array){
  45. $return = array() ;
  46. $paths = $json_array['paths'] ;
  47. foreach ($paths as $url => $value) {
  48. foreach ($value as $method => $value2) {
  49. $return[] = $this->_requestToDoc($method , $url , $value2 , $json_array);
  50. }
  51. }
  52. return $return ;
  53. }
  54. private function _requestToDoc($method , $url , $request , $json_array){
  55. $from = I("from") ? I("from") : '' ;
  56. if($from == 'runapi'){
  57. return $this->_requestToApi($method , $url , $request , $json_array);
  58. //如果是来自runapi的导入请求,则已经return不再执行下面
  59. }
  60. $return = array() ;
  61. $return['page_title'] = $request['summary'] ;
  62. $return['s_number'] = 99 ;
  63. $return['page_comments'] = '' ;
  64. $content = '
  65. **简要描述:**
  66. - '.$request['description'].'
  67. **请求URL:**
  68. - ` '.$url.' `
  69. **请求方式:**
  70. - '.$method.' ';
  71. if ($request['header']) {
  72. $content .='
  73. **Header:**
  74. |Header名|是否必选|类型|说明|
  75. |:---- |:---|:----- |----- |'."\n";
  76. foreach ($request['headerData'] as $key => $value) {
  77. $content .= '|'.$value["key"].' | | text | '.$value["value"].' |'."\n";
  78. }
  79. }
  80. if ($request['rawModeData']) {
  81. $content .= '
  82. **请求参数示例**
  83. ```
  84. '.$request['rawModeData'].'
  85. ```
  86. ';
  87. }
  88. if ($request['parameters']) {
  89. $content .='
  90. **参数:**
  91. |参数名|是否必选|类型|说明|
  92. |:---- |:---|:----- |----- |'."\n";
  93. foreach ($request['parameters'] as $key => $value) {
  94. $content .= '|'.$value["name"].' | '.($value["required"] ? '是' : '否' ).' |'.$value["type"].' | '.$value["description"].' |'."\n";
  95. }
  96. }
  97. if ($request['responses']['200']) {
  98. $responses = $request['responses']['200'] ;
  99. //如果返回信息是引用对象
  100. if ($request['responses']['200']['schema'] && $request['responses']['200']['schema']['$ref'] ) {
  101. $str_array = explode("/", $request['responses']['200']['schema']['$ref']) ;
  102. if ($str_array[1] && $str_array[2]) {
  103. $responses = $json_array[$str_array[1]][$str_array[2]] ;
  104. $content .='
  105. **返回参数说明:**
  106. |参数名|类型|说明|
  107. |:---- |:---|:----- |----- |'."\n";
  108. foreach ($responses['properties'] as $key => $value) {
  109. $content .= '|'.$key.'|'.$value["type"].' | '.$value["description"].' |'."\n";
  110. }
  111. }
  112. }else{
  113. //如果返回的是普通json
  114. $content .= '
  115. **返回示例**
  116. ```
  117. '.$this->_indent_json(json_encode($responses)).'
  118. ```
  119. ';
  120. }
  121. }
  122. $return['page_content'] = $content ;
  123. return $return ;
  124. }
  125. private function _requestToApi($method , $url , $request , $json_array){
  126. $return = array() ;
  127. $return['page_title'] = $request['summary'] ;
  128. $return['s_number'] = 99 ;
  129. $return['page_comments'] = '' ;
  130. $content_array = array(
  131. "info"=>array(
  132. "from" => 'runapi' ,
  133. "type" => 'api' ,
  134. "title" => $request['summary'] ,
  135. "description" => $request['description'] ,
  136. "method" => strtolower($method) ,
  137. "url" => $url ,
  138. "remark" => '' ,
  139. ),
  140. "request" =>array(
  141. "params"=> array(
  142. 'mode' => "formdata",
  143. 'json' => "",
  144. 'urlencoded' => array(),
  145. 'formdata' => array(),
  146. ),
  147. "headers"=> array(),
  148. "cookies"=> array(),
  149. "auth"=> array(),
  150. ),
  151. "response" =>array(),
  152. "extend" =>array(),
  153. );
  154. if ($request['headerData']) {
  155. $tmp_array = array();
  156. foreach ($request['headerData'] as $key => $value) {
  157. $content_array['request']['headers'][] = array(
  158. "name" =>$value["key"],
  159. "type" =>'string',
  160. "value" =>$value["value"],
  161. "require" =>'1',
  162. "remark" =>'',
  163. );
  164. }
  165. }
  166. if ($request['parameters']) {
  167. foreach ($request['parameters'] as $key => $value) {
  168. $content_array['request']['params']['formdata'][] = array(
  169. "name" =>$value["name"],
  170. "type" =>'string',
  171. "value" =>$value["value"],
  172. "require" =>'1',
  173. "remark" =>$value["description"],
  174. );
  175. }
  176. }
  177. $return['page_content'] = json_encode($content_array);
  178. return $return ;
  179. }
  180. /**
  181. * Indents a flat JSON string to make it more human-readable.
  182. *
  183. * @param string $json The original JSON string to process.
  184. *
  185. * @return string Indented version of the original JSON string.
  186. */
  187. private function _indent_json($json) {
  188. $result = '';
  189. $pos = 0;
  190. $strLen = strlen($json);
  191. $indentStr = ' ';
  192. $newLine = "\n";
  193. $prevChar = '';
  194. $outOfQuotes = true;
  195. for ($i=0; $i<=$strLen; $i++) {
  196. // Grab the next character in the string.
  197. $char = substr($json, $i, 1);
  198. // Are we inside a quoted string?
  199. if ($char == '"' && $prevChar != '\\') {
  200. $outOfQuotes = !$outOfQuotes;
  201. // If this character is the end of an element,
  202. // output a new line and indent the next line.
  203. } else if(($char == '}' || $char == ']') && $outOfQuotes) {
  204. $result .= $newLine;
  205. $pos --;
  206. for ($j=0; $j<$pos; $j++) {
  207. $result .= $indentStr;
  208. }
  209. }
  210. // Add the character to the result string.
  211. $result .= $char;
  212. // If the last character was the beginning of an element,
  213. // output a new line and indent the next line.
  214. if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) {
  215. $result .= $newLine;
  216. if ($char == '{' || $char == '[') {
  217. $pos ++;
  218. }
  219. for ($j = 0; $j < $pos; $j++) {
  220. $result .= $indentStr;
  221. }
  222. }
  223. $prevChar = $char;
  224. }
  225. return $result;
  226. }
  227. }