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.

327 lines
10 KiB

3 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" => $this->_getAllTagsLogs($json_array)
  30. )
  31. ) ;
  32. $level = 2 ;
  33. // $item_array['pages']['catalogs'][0]['pages'] = $this->_getPageByPaths($json_array);
  34. $item_id = D("Item")->import( json_encode($item_array) , $login_user['uid'] );
  35. //echo D("Item")->export(196053901215026 );
  36. //echo json_encode($item_array);
  37. $this->sendResult(array('item_id' => $item_id));
  38. }
  39. private function _getAllTagsLogs($json_array) {
  40. $catalogsMap = array(
  41. "fromSwagger" => array("cat_name" =>'from swagger', "pages" =>array())
  42. );
  43. $paths = $json_array['paths'] ;
  44. foreach ($paths as $url => $value) {
  45. foreach ($value as $method => $value2) {
  46. $tags = isset($value2["tags"]) ? $value2["tags"] : array();
  47. if ($tags == array()){
  48. $page = $this->_requestToDoc($method, $url, $value2, $json_array);
  49. if($page['page_title']){
  50. $catalogsMap["fromSwagger"]["pages"][] = $page;
  51. }
  52. }else{
  53. foreach ($tags as $tag){
  54. if (!key_exists($tag, $catalogsMap)) {
  55. $page = $this->_requestToDoc($method, $url, $value2, $json_array);
  56. if ($page["page_title"] != "" && $page["page_content"] != ""){
  57. $catalogsMap[$tag] = array("cat_name" => $tag, "pages" => array($page));
  58. }
  59. }else{
  60. // 存在则page merge
  61. $page = $this->_requestToDoc($method, $url, $value2, $json_array);
  62. if ($page["page_title"] != "" && $page["page_content"] != ""){
  63. $catalogsMap[$tag]["pages"][] = $page;
  64. }
  65. }
  66. }
  67. }
  68. }
  69. }
  70. $catalogs = array();
  71. foreach ($catalogsMap as $key => $value){
  72. $catalogs[] = $value;
  73. }
  74. return $catalogs;
  75. }
  76. private function _getPageByPaths($json_array){
  77. $return = array() ;
  78. $paths = $json_array['paths'] ;
  79. foreach ($paths as $url => $value) {
  80. foreach ($value as $method => $value2) {
  81. $return[] = $this->_requestToDoc($method , $url , $value2 , $json_array);
  82. }
  83. }
  84. return $return ;
  85. }
  86. private function _requestToDoc($method , $url , $request , $json_array){
  87. $from = I("from") ? I("from") : '' ;
  88. if($from == 'runapi'){
  89. return $this->_requestToApi($method , $url , $request , $json_array);
  90. //如果是来自runapi的导入请求,则已经return不再执行下面
  91. }
  92. $return = array() ;
  93. $return['page_title'] = $request['summary'] ? $request['summary']: $request['operationId'] ;
  94. $return['s_number'] = 99 ;
  95. $return['page_comments'] = '' ;
  96. $content = '
  97. **简要描述:**
  98. - '.$request['description'].'
  99. **请求URL:**
  100. - ` '.$url.' `
  101. **请求方式:**
  102. - '.$method.' ';
  103. if ($request['header']) {
  104. $content .='
  105. **Header:**
  106. |Header名|是否必选|类型|说明|
  107. |:---- |:---|:----- |----- |'."\n";
  108. foreach ($request['headerData'] as $key => $value) {
  109. $content .= '|'.$value["key"].' | | text | '.$value["value"].' |'."\n";
  110. }
  111. }
  112. if ($request['rawModeData']) {
  113. $content .= '
  114. **请求参数示例**
  115. ```
  116. '.$request['rawModeData'].'
  117. ```
  118. ';
  119. }
  120. if ($request['parameters']) {
  121. $content .='
  122. **参数:**
  123. |参数名|是否必选|类型|说明|
  124. |:---- |:---|:----- |----- |'."\n";
  125. foreach ($request['parameters'] as $key => $value) {
  126. $content .= '|'.$value["name"].' | '.($value["required"] ? '是' : '否' ).' |'.$value["type"].' | '.$value["description"].' |'."\n";
  127. }
  128. }
  129. if ($request['responses']['200']) {
  130. $responses = $request['responses']['200'] ;
  131. //如果返回信息是引用对象
  132. if ($request['responses']['200']['schema'] && $request['responses']['200']['schema']['$ref'] ) {
  133. $str_array = explode("/", $request['responses']['200']['schema']['$ref']) ;
  134. if ($str_array[1] && $str_array[2]) {
  135. $responses = $json_array[$str_array[1]][$str_array[2]] ;
  136. $content .='
  137. **返回参数说明:**
  138. |参数名|类型|说明|
  139. |:---- |:---|:----- |----- |'."\n";
  140. foreach ($responses['properties'] as $key => $value) {
  141. $content .= '|'.$key.'|'.$value["type"].' | '.$value["description"].' |'."\n";
  142. }
  143. }
  144. }else{
  145. //如果返回的是普通json
  146. $content .= '
  147. **返回示例**
  148. ```
  149. '.$this->_indent_json(json_encode($responses)).'
  150. ```
  151. ';
  152. }
  153. }
  154. $return['page_content'] = $content ;
  155. return $return ;
  156. }
  157. private function _requestToApi($method , $url , $request , $json_array){
  158. $return = array() ;
  159. $return['page_title'] = $request['summary'] ? $request['summary']: $request['operationId'] ;
  160. $return['s_number'] = 99 ;
  161. $return['page_comments'] = '' ;
  162. $content_array = array(
  163. "info"=>array(
  164. "from" => 'runapi' ,
  165. "type" => 'api' ,
  166. "title" => $request['summary'] ? $request['summary']: $request['operationId'] ,
  167. "description" => $request['description'] ,
  168. "method" => strtolower($method) ,
  169. "url" => $url ,
  170. "remark" => '' ,
  171. ),
  172. "request" =>array(
  173. "params"=> array(
  174. 'mode' => "formdata",
  175. 'json' => "",
  176. 'urlencoded' => array(),
  177. 'formdata' => array(),
  178. ),
  179. "headers"=> array(),
  180. "cookies"=> array(),
  181. "auth"=> array(),
  182. ),
  183. "response" =>array(),
  184. "extend" =>array(),
  185. );
  186. if ($request['headerData']) {
  187. $tmp_array = array();
  188. foreach ($request['headerData'] as $key => $value) {
  189. $content_array['request']['headers'][] = array(
  190. "name" =>$value["key"],
  191. "type" =>'string',
  192. "value" =>$value["value"],
  193. "require" =>'1',
  194. "remark" =>'',
  195. );
  196. }
  197. }
  198. if ($request['parameters']) {
  199. foreach ($request['parameters'] as $key => $value) {
  200. $content_array['request']['params']['formdata'][] = array(
  201. "name" =>$value["name"],
  202. "type" =>'string',
  203. "value" =>$value["value"],
  204. "require" =>'1',
  205. "remark" =>$value["description"],
  206. );
  207. }
  208. }
  209. $return['page_content'] = json_encode($content_array);
  210. return $return ;
  211. }
  212. /**
  213. * Indents a flat JSON string to make it more human-readable.
  214. *
  215. * @param string $json The original JSON string to process.
  216. *
  217. * @return string Indented version of the original JSON string.
  218. */
  219. private function _indent_json($json) {
  220. $result = '';
  221. $pos = 0;
  222. $strLen = strlen($json);
  223. $indentStr = ' ';
  224. $newLine = "\n";
  225. $prevChar = '';
  226. $outOfQuotes = true;
  227. for ($i=0; $i<=$strLen; $i++) {
  228. // Grab the next character in the string.
  229. $char = substr($json, $i, 1);
  230. // Are we inside a quoted string?
  231. if ($char == '"' && $prevChar != '\\') {
  232. $outOfQuotes = !$outOfQuotes;
  233. // If this character is the end of an element,
  234. // output a new line and indent the next line.
  235. } else if(($char == '}' || $char == ']') && $outOfQuotes) {
  236. $result .= $newLine;
  237. $pos --;
  238. for ($j=0; $j<$pos; $j++) {
  239. $result .= $indentStr;
  240. }
  241. }
  242. // Add the character to the result string.
  243. $result .= $char;
  244. // If the last character was the beginning of an element,
  245. // output a new line and indent the next line.
  246. if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) {
  247. $result .= $newLine;
  248. if ($char == '{' || $char == '[') {
  249. $pos ++;
  250. }
  251. for ($j = 0; $j < $pos; $j++) {
  252. $result .= $indentStr;
  253. }
  254. }
  255. $prevChar = $char;
  256. }
  257. return $result;
  258. }
  259. }