ImportSwaggerController.class.php 9.7 KB

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