SystemRouteServices.php 20 KB

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