SystemRouteServices.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. <?php
  2. /**
  3. * +----------------------------------------------------------------------
  4. * | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  5. * +----------------------------------------------------------------------
  6. * | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
  7. * +----------------------------------------------------------------------
  8. * | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  9. * +----------------------------------------------------------------------
  10. * | Author: CRMEB Team <admin@crmeb.com>
  11. * +----------------------------------------------------------------------
  12. */
  13. namespace app\services\system;
  14. use app\dao\system\SystemRouteDao;
  15. use app\services\BaseServices;
  16. use crmeb\services\CacheService;
  17. use crmeb\services\FormBuilder;
  18. use think\exception\ValidateException;
  19. use think\helper\Str;
  20. /**
  21. * Class SystemRouteServices
  22. * @author 等风来
  23. * @email 136327134@qq.com
  24. * @date 2023/4/6
  25. * @package app\services\system
  26. */
  27. class SystemRouteServices extends BaseServices
  28. {
  29. /**
  30. * SystemRouteServices constructor.
  31. * @param SystemRouteDao $dao
  32. */
  33. public function __construct(SystemRouteDao $dao)
  34. {
  35. $this->dao = $dao;
  36. }
  37. /**
  38. * @param array $where
  39. * @return array
  40. * @author 等风来
  41. * @email 136327134@qq.com
  42. * @date 2023/4/7
  43. */
  44. public function getList(array $where)
  45. {
  46. [$page, $limit] = $this->getPageValue();
  47. $list = $this->dao->selectList($where, 'name,path,method', $page, $limit)->toArray();
  48. $count = $this->dao->count($where);
  49. return compact('list', 'count');
  50. }
  51. /**
  52. * @param int $id
  53. * @return array
  54. * @author 等风来
  55. * @email 136327134@qq.com
  56. * @date 2023/4/10
  57. */
  58. public function getInfo(int $id)
  59. {
  60. $routeInfo = $this->dao->get($id);
  61. if (!$routeInfo) {
  62. throw new ValidateException(500036);
  63. }
  64. $routeInfo = $routeInfo->toArray();
  65. $routeInfo['cate_tree'] = app()->make(SystemRouteCateServices::class)->getAllList($routeInfo['app_name'], 'id,name,pid', 'id asc,sort desc');
  66. return $routeInfo;
  67. }
  68. /**
  69. * 获取tree数据
  70. * @param string $appName
  71. * @param string $name
  72. * @return mixed
  73. * @author 吴汐
  74. * @email 442384644@qq.com
  75. * @date 2023/05/06
  76. */
  77. public function getTreeList(string $appName = 'adminapi', string $name = '')
  78. {
  79. return CacheService::remember('ROUTE_LIST' . strtoupper($appName), function () use ($name, $appName) {
  80. $list = app()->make(SystemRouteCateServices::class)
  81. ->selectList(['app_name' => $appName], '*', 0, 0, 'id asc,sort desc', [
  82. 'children' => function ($query) use ($name, $appName) {
  83. $query->where('app_name', $appName)
  84. ->when('' !== $name, function ($q) use ($name) {
  85. $q->where('name|path', 'LIKE', '%' . $name . '%');
  86. });
  87. }
  88. ])
  89. ->toArray();
  90. foreach ($list as $key => $item) {
  91. if (!empty($item['children'])) {
  92. foreach ($item['children'] as $k => $v) {
  93. if (isset($v['cate_id']) && isset($v['method'])) {
  94. if ($v['method'] === 'DELETE') {
  95. $v['method'] = 'DEL';
  96. }
  97. $v['pid'] = $v['cate_id'];
  98. $list[$key]['children'][$k] = $v;
  99. }
  100. }
  101. }
  102. }
  103. return get_tree_children($list);
  104. }, 600);
  105. }
  106. /**
  107. * @param array $importData
  108. * @return bool
  109. * @author 等风来
  110. * @email 136327134@qq.com
  111. * @date 2023/4/26
  112. */
  113. public function importData(array $importData)
  114. {
  115. foreach ($importData as $item) {
  116. $id = $this->dao->value(['method' => $item['method'], 'path' => $item['path']], 'id');
  117. if ($id) {
  118. $this->dao->update($id, [
  119. 'query' => $item['query'],
  120. 'header' => $item['header'],
  121. 'request' => $item['request'],
  122. 'response' => $item['response'],
  123. 'request_type' => $item['request_type'],
  124. 'response_example' => $item['response_example'],
  125. ]);
  126. }
  127. }
  128. return true;
  129. }
  130. /**
  131. * 获取某个应用下的所有路由权限
  132. * @param string $app
  133. * @return array
  134. * @author 等风来
  135. * @email 136327134@qq.com
  136. * @date 2023/4/6
  137. */
  138. public function getRouteListAll(string $app = 'adminapi')
  139. {
  140. //获取所有的路由
  141. $this->app = app();
  142. $this->app->route->setTestMode(true);
  143. $this->app->route->clear();
  144. $path = $this->app->getRootPath() . 'app' . DS . $app . DS . 'route' . DS;
  145. $files = is_dir($path) ? scandir($path) : [];
  146. foreach ($files as $file) {
  147. if (strpos($file, '.php')) {
  148. include $path . $file;
  149. }
  150. }
  151. $route = $this->app->route->getRuleList();
  152. $action_arr = ['index', 'read', 'create', 'save', 'edit', 'update', 'delete'];
  153. foreach ($route as $key => $item) {
  154. $real_name = $item['option']['real_name'] ?? '';
  155. if (is_array($real_name)) {
  156. foreach ($action_arr as $a) {
  157. if (Str::contains($item['route'], $a)) {
  158. $real_name = $real_name[$a] ?? '';
  159. }
  160. }
  161. }
  162. $item['option']['real_name'] = $real_name;
  163. $route[$key] = $item;
  164. $except = $item['option']['except'] ?? [];
  165. $router = is_string($item['route']) ? explode('/', $item['route']) : [];
  166. $action = $router[count($router) - 1] ?? null;
  167. //去除不需要的路由
  168. if ($except && $action && in_array($action, $except)) {
  169. unset($route[$key]);
  170. }
  171. $only = $item['option']['only'] ?? [];
  172. if ($only && $action && !in_array($action, $only)) {
  173. unset($route[$key]);
  174. }
  175. }
  176. return $route;
  177. }
  178. /**
  179. * 获取顶级id
  180. * @param string $app
  181. * @return mixed
  182. * @author 等风来
  183. * @email 136327134@qq.com
  184. * @date 2023/4/11
  185. */
  186. public function topCateId(string $app, string $cateName, int $pid = 0)
  187. {
  188. $oneId = app()->make(SystemRouteCateServices::class)->value(['app_name' => $app, 'name' => $cateName, 'pid' => 0], 'id');
  189. if (!$oneId) {
  190. //修复重复同步后反复增加二级文件夹
  191. $id = app()->make(SystemRouteCateServices::class)->value(['app_name' => $app, 'name' => $cateName, 'pid' => $pid], 'id');
  192. if ($id) return $id;
  193. $res = app()->make(SystemRouteCateServices::class)->save([
  194. 'app_name' => $app,
  195. 'name' => $cateName,
  196. 'pid' => $pid,
  197. 'add_time' => time(),
  198. ]);
  199. return $res->id;
  200. }
  201. return $oneId;
  202. }
  203. /**
  204. * 同步路由
  205. * @author 等风来
  206. * @email 136327134@qq.com
  207. * @date 2023/4/6
  208. */
  209. public function syncRoute(string $app = 'adminapi')
  210. {
  211. $listAll = $this->getRouteListAll($app);
  212. $list = [];
  213. foreach ($listAll as $item) {
  214. if (!isset($item['option']['mark_name']) || strstr($item['rule'], '<MISS>') !== false) {
  215. continue;
  216. } else {
  217. $list[$item['option']['mark_name']][] = $item;
  218. }
  219. }
  220. $newsList = [];;
  221. foreach ($list as $key => $item) {
  222. $newItem = [];
  223. foreach ($item as $value) {
  224. if (isset($value['option']['cate_name'])) {
  225. $newItem[$value['option']['cate_name']][] = $value;
  226. } else {
  227. $newItem[$key][] = $value;
  228. }
  229. }
  230. $newsList[$key] = $newItem;
  231. }
  232. $list = [];
  233. foreach ($newsList as $key => $item) {
  234. $keys = array_keys($item);
  235. $pid = $this->topCateId($app, $key, 0);
  236. if ($keys == 1 && $key == $keys[0]) {
  237. foreach ($item[$key] as $value) {
  238. $list[$pid][] = $value;
  239. }
  240. } else {
  241. foreach ($item as $i => $k) {
  242. $cateId = $this->topCateId($app, $i, $pid);
  243. foreach ($k as $value) {
  244. $list[$cateId][] = $value;
  245. }
  246. }
  247. }
  248. }
  249. //保持新增的权限路由
  250. $data = $this->dao->selectList(['app_name' => $app], 'path,method')->toArray();
  251. $save = [];
  252. foreach ($list as $key => $value) {
  253. foreach ($value as $item) {
  254. if (!$this->diffRoute($data, $item['rule'], $item['method']) && strstr($item['rule'], '<MISS>') === false) {
  255. $pathAndAction = explode('/', $item['route']);
  256. $save[] = [
  257. 'name' => $item['option']['real_name'] ?? $item['name'],
  258. 'path' => $item['rule'],
  259. 'cate_id' => $key,
  260. 'app_name' => $app,
  261. 'file_path' => 'app/' . $app . '/controller/' . str_replace('.', '/', $pathAndAction[0]) . '.php',
  262. 'action' => $pathAndAction[1],
  263. 'type' => isset($item['option']['is_common']) && $item['option']['is_common'] ? 1 : 0,
  264. 'method' => $item['method'],
  265. 'add_time' => date('Y-m-d H:i:s'),
  266. ];
  267. }
  268. }
  269. }
  270. if ($save) {
  271. $this->dao->saveAll($save);
  272. }
  273. //删除不存在的权限路由
  274. $data = $this->dao->selectList(['app_name' => $app], 'path,method,id')->toArray();
  275. $delete = [];
  276. $deleteData = [];
  277. foreach ($data as $item) {
  278. if (!$this->diffRoute($listAll, $item['path'], $item['method'], 'rule') && $item['path'] !== '<MISS>') {
  279. $delete[] = $item['id'];
  280. $deleteData[] = [
  281. 'path' => $item['path'],
  282. 'method' => $item['method']
  283. ];
  284. }
  285. }
  286. //删除不存在的路由
  287. if ($delete) {
  288. $this->dao->delete([['id', 'in', $delete]]);
  289. }
  290. //删除不存在的权限
  291. if ($deleteData) {
  292. foreach ($deleteData as $item) {
  293. app()->make(SystemMenusServices::class)->deleteMenu($item['path'], $item['method']);
  294. }
  295. }
  296. CacheService::clear();
  297. }
  298. /**
  299. * 对比路由
  300. * @param array $data
  301. * @param string $path
  302. * @param string $method
  303. * @return bool
  304. * @author 等风来
  305. * @email 136327134@qq.com
  306. * @date 2023/4/6
  307. */
  308. protected function diffRoute(array $data, string $path, string $method, string $key = 'path')
  309. {
  310. $res = false;
  311. foreach ($data as $item) {
  312. if (strtolower($item['method']) == strtolower($method) && strtolower($item[$key]) == strtolower($path)) {
  313. $res = true;
  314. break;
  315. } else if ($method === '*' && strtolower($item[$key]) == strtolower($path)) {
  316. $res = true;
  317. break;
  318. }
  319. }
  320. return $res;
  321. }
  322. /**
  323. * 添加和修改路由
  324. * @param int $id
  325. * @return array
  326. * @author 等风来
  327. * @email 136327134@qq.com
  328. * @date 2023/4/7
  329. */
  330. public function getFrom(int $id = 0, string $appName = 'adminapi')
  331. {
  332. $cateList = app()->make(SystemRouteCateServices::class)->getAllList($appName, 'name as label,path as value');
  333. $url = '/system/route';
  334. $routeInfo = [];
  335. if ($id) {
  336. $routeInfo = $this->dao->get($id);
  337. $routeInfo = $routeInfo ? $routeInfo->toArray() : [];
  338. $url .= '/' . $id;
  339. }
  340. $rule = [
  341. FormBuilder::cascader('cate_id', '分类', $routeInfo['cate_id'] ?? 0)->data($cateList),
  342. FormBuilder::input('name', '路由名称', $routeInfo['name'] ?? '')->required(),
  343. FormBuilder::input('path', '路由路径', $routeInfo['path'] ?? '')->required(),
  344. FormBuilder::select('method', '请求方式', $routeInfo['method'] ?? '')->options([
  345. ['value' => 'POST', 'label' => 'POST'],
  346. ['value' => 'GET', 'label' => 'GET'],
  347. ['value' => 'DELETE', 'label' => 'DELETE'],
  348. ['value' => 'PUT', 'label' => 'PUT'],
  349. ['value' => '*', 'label' => '*'],
  350. ])->required(),
  351. FormBuilder::radio('type', '类型', $routeInfo['type'] ?? 0)->options([
  352. ['value' => 0, 'lable' => '普通路由'],
  353. ['value' => 1, 'lable' => '公共路由'],
  354. ]),
  355. FormBuilder::hidden('app_name', $appName),
  356. ];
  357. return create_form($id ? '修改路由' : '添加路由', $rule, $url, $id ? 'PUT' : 'POST');
  358. }
  359. /**
  360. * 导入数据
  361. * @param string $filePath
  362. * @return mixed
  363. * @author 等风来
  364. * @email 136327134@qq.com
  365. * @date 2023/4/26
  366. */
  367. public function import(string $filePath)
  368. {
  369. $preg = '/\{+[a-zA-Z0-9]+\}/';
  370. $res = file_get_contents(app()->getRootPath() . $filePath);
  371. $res = json_decode($res, true);
  372. $data = $res['apiCollection'][0]['items'];
  373. $route = [];
  374. foreach ($data as $item) {
  375. foreach ($item['items'] as $value) {
  376. if (isset($value['api'])) {
  377. $path = str_replace('//', '/', str_replace('{}', '', $value['api']['path']));
  378. $paramePath = $this->getPathValue($value['api']['parameters']['path'] ?? []);
  379. if (strstr($path, ':') !== false) {
  380. $path = str_replace(':', '', $path);
  381. }
  382. if (preg_match_all($preg, $path, $matches)) {
  383. $paramePathMatche = [];
  384. if (isset($matches[0]) && $matches[0]) {
  385. foreach ($matches[0] as $v) {
  386. $paramePathMatche[] = str_replace(['{', '}'], ['<', '>'], $v);
  387. }
  388. }
  389. if ($paramePathMatche) {
  390. $paramePath = implode('/', $paramePathMatche);
  391. }
  392. }
  393. if ($path[0] === '/') {
  394. $path = substr($path, 1);
  395. }
  396. $route[] = [
  397. 'method' => strtoupper($value['api']['method']),
  398. 'path' => $path . $paramePath,
  399. 'request_type' => $value['api']['requestBody']['type'],
  400. 'query' => $this->getParameters($value['api'], $res['commonParameters'] ?: []),
  401. 'header' => $this->getParameters($value['api'], $res['commonParameters'] ?: [], 'header'),
  402. 'request' => $this->getRequest($value['api']['requestBody'] ?? []),
  403. 'response' => $this->getResponse($value['api']['responses'][0]['jsonSchema']['properties'] ?? []),
  404. 'response_example' => $this->getResponseExample($value['api']['responseExamples'] ?? []),
  405. ];
  406. }
  407. }
  408. }
  409. return $this->importData($route);
  410. }
  411. protected function getParameters(array $api, array $commonParameters = [], string $type = 'query', $parentId = '')
  412. {
  413. $parameters = [];
  414. // 获取参数
  415. if (!empty($api['parameters'][$type])) {
  416. foreach ($api['parameters'][$type] as $key => $option) {
  417. $id = uniqid();
  418. $parameters[] = [
  419. 'attribute' => $option['name'],
  420. 'type' => $option['type'],
  421. 'trip' => $option['description'] ?? '',
  422. 'value' => $option['example'] ?? '',
  423. 'must' => empty($option['enable']) ? "0" : "1",
  424. 'id' => $id,
  425. 'parentId' => $parentId,
  426. ];
  427. }
  428. }
  429. // 获取公共参数
  430. if (!empty($api['commonParameters'][$type]) && !empty($commonParameters['parameters'][$type])) {
  431. foreach ($api['commonParameters'][$type] as $key => $option) {
  432. // 获取common参数
  433. foreach ($commonParameters['parameters'][$type] as $parameter) {
  434. if ($parameter['name'] == $option['name']) {
  435. $id = uniqid();
  436. $parameters[] = [
  437. 'attribute' => $parameter['name'],
  438. 'type' => $parameter['type'],
  439. 'trip' => $parameter['description'] ?? '',
  440. 'value' => $parameter['defaultValue'] ?? '',
  441. 'must' => empty($parameter['enable']) ? '0' : "1",
  442. 'id' => $id,
  443. 'parentId' => $parentId,
  444. ];
  445. }
  446. }
  447. }
  448. }
  449. return $parameters;
  450. }
  451. /**
  452. * 获取请求返回数据
  453. * @param array $options
  454. * @param string $parentId
  455. * @return array
  456. * @author 等风来
  457. * @email 136327134@qq.com
  458. * @date 2023/4/26
  459. */
  460. protected function getResponse(array $options, $parentId = '')
  461. {
  462. $response = [];
  463. foreach ($options as $key => $option) {
  464. $id = uniqid();
  465. $response[] = [
  466. 'attribute' => $key,
  467. 'type' => $option['type'],
  468. 'trip' => $option['description'] ?? '',
  469. 'id' => $id,
  470. 'parentId' => $parentId,
  471. ];
  472. if (isset($option['items']['properties'])) {
  473. $option['properties'] = $option['items']['properties'];
  474. }
  475. if (isset($option['properties'])) {
  476. $response = array_merge($response, $this->getResponse($option['properties'], $id));
  477. }
  478. }
  479. return $response;
  480. }
  481. /**
  482. * 获取请求数据
  483. * @param array $options
  484. * @return array
  485. * @author 等风来
  486. * @email 136327134@qq.com
  487. * @date 2023/4/26
  488. */
  489. protected function getRequest(array $options)
  490. {
  491. $parameters = $options['parameters'] ?? [];
  492. $jsonSchema = $options['jsonSchema']['properties'] ?? [];
  493. $request = [];
  494. foreach ($parameters as $option) {
  495. $request[] = [
  496. 'attribute' => $option['name'],
  497. 'type' => $option['type'] === 'text' ? 'string' : $option['type'],
  498. 'must' => 0,
  499. 'trip' => $option['description'],
  500. 'id' => $option['id'],
  501. ];
  502. }
  503. foreach ($jsonSchema as $key => $json_option) {
  504. $request[] = [
  505. 'attribute' => $key,
  506. 'type' => $json_option['type'] === 'text' ? 'string' : $json_option['type'],
  507. 'must' => 0,
  508. 'trip' => $json_option['description'] ?? '',
  509. 'id' => uniqid(),
  510. ];
  511. }
  512. return $request;
  513. }
  514. /**
  515. * 处理path路径
  516. * @param array $options
  517. * @return string
  518. * @author 等风来
  519. * @email 136327134@qq.com
  520. * @date 2023/4/26
  521. */
  522. protected function getPathValue(array $options)
  523. {
  524. $path = [];
  525. foreach ($options as $option) {
  526. if (strstr($option['name'], '?') !== false) {
  527. $option['name'] = str_replace('?', '', $option['name']) . '?';
  528. }
  529. $path[] = '<' . $option['name'] . '>';
  530. }
  531. return implode('/', $path);
  532. }
  533. protected function getResponseExample($options)
  534. {
  535. $example = [];
  536. foreach ($options as $option) {
  537. if (empty($examples)) {
  538. $example[] = [
  539. 'name' => $option['name'],
  540. 'data' => json_decode($option['data'], true),
  541. ];
  542. }
  543. }
  544. return $example;
  545. }
  546. }