SystemCrudServices.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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\SystemCrudDao;
  15. use app\services\BaseServices;
  16. use crmeb\services\crud\Controller;
  17. use crmeb\services\crud\Dao;
  18. use crmeb\services\crud\Make;
  19. use crmeb\services\crud\Model;
  20. use crmeb\services\crud\Route;
  21. use crmeb\services\crud\Service;
  22. use crmeb\services\crud\Validate;
  23. use crmeb\services\crud\ViewApi;
  24. use crmeb\services\crud\ViewPages;
  25. use crmeb\services\crud\ViewRouter;
  26. use think\exception\ValidateException;
  27. use think\facade\Db;
  28. use think\helper\Str;
  29. use think\migration\Migrator;
  30. use Phinx\Db\Adapter\MysqlAdapter;
  31. /**
  32. * Class SystemCrudServices
  33. * @author 等风来
  34. * @email 136327134@qq.com
  35. * @date 2023/4/6
  36. * @package app\services\system
  37. */
  38. class SystemCrudServices extends BaseServices
  39. {
  40. //不能生成的系统自带表
  41. const NOT_CRUD_TABANAME = [
  42. 'system_config', 'system_attachment', 'system_attachment_category', 'system_config_tab',
  43. 'system_admin', 'eb_system_city', 'system_log', 'system_menus', 'system_notice',
  44. 'system_notice_admin', 'system_notification', 'system_role', 'system_route',
  45. 'system_route_cate', 'system_storage', 'system_timer', 'system_user_level',
  46. 'system_crud', 'wechat_key', 'user_label_relation', 'user_brokerage_frozen',
  47. 'user_brokerage', 'store_product_cate', 'store_bargain_user_help', 'shipping_templates_region',
  48. 'shipping_templates_no_delivery', 'shipping_templates_free', 'other_order_status', 'lang_code',
  49. 'lang_country', 'app_version',
  50. ];
  51. /**
  52. * SystemCrudServices constructor.
  53. * @param SystemCrudDao $dao
  54. */
  55. public function __construct(SystemCrudDao $dao)
  56. {
  57. $this->dao = $dao;
  58. }
  59. /**
  60. * @return array
  61. * @author 等风来
  62. * @email 136327134@qq.com
  63. * @date 2023/4/11
  64. */
  65. public function getList()
  66. {
  67. [$page, $limit] = $this->getPageValue();
  68. $list = $this->dao->selectList([], 'add_time,id,name,table_name', $page, $limit, 'id desc');
  69. $count = $this->dao->count();
  70. return compact('list', 'count');
  71. }
  72. /**
  73. * 数据库字段类型
  74. * @return \string[][]
  75. * @author 等风来
  76. * @email 136327134@qq.com
  77. * @date 2023/4/11
  78. */
  79. public function getTabelRule()
  80. {
  81. return [
  82. 'types' => [
  83. 'string',
  84. 'char',
  85. 'text',
  86. 'integer',
  87. 'biginteger',
  88. 'float',
  89. 'decimal',
  90. 'datetime',
  91. 'timestamp',
  92. 'time',
  93. 'date',
  94. 'blob',
  95. 'binary',
  96. 'varbinary',
  97. 'boolean',
  98. 'uuid',
  99. // Geospatial data types
  100. 'geometry',
  101. 'point',
  102. 'linestring',
  103. 'polygon',
  104. ]
  105. ];
  106. }
  107. /**
  108. * 获取表字段
  109. * @param string $tableName
  110. * @return mixed
  111. * @author 等风来
  112. * @email 136327134@qq.com
  113. * @date 2023/4/7
  114. */
  115. public function getColumnNamesList(string $tableName)
  116. {
  117. $sql = 'SELECT * FROM `information_schema`.`columns` WHERE TABLE_SCHEMA = ? AND table_name = ? ORDER BY ORDINAL_POSITION';
  118. $column = Db::query($sql, [config('database.connections.mysql.database'), $this->getTableName($tableName)]);
  119. $columns = [];
  120. foreach ($column as $item) {
  121. $column = [
  122. 'name' => $item['COLUMN_NAME'],
  123. 'type' => $item['DATA_TYPE'],
  124. 'dataType' => stripos($item['COLUMN_TYPE'], '(') !== false ? substr_replace($item['COLUMN_TYPE'], '', stripos($item['COLUMN_TYPE'], ')') + 1) : $item['COLUMN_TYPE'],
  125. 'default' => $item['COLUMN_DEFAULT'],
  126. 'null' => $item['IS_NULLABLE'] == 'YES',
  127. 'primaryKey' => $item['COLUMN_KEY'] == 'PRI',
  128. 'unsigned' => (bool)stripos($item['COLUMN_TYPE'], 'unsigned'),
  129. 'autoIncrement' => stripos($item['EXTRA'], 'auto_increment') !== false,
  130. 'comment' => $item['COLUMN_COMMENT'],
  131. ];
  132. $columns[$item['COLUMN_NAME']] = $column;
  133. }
  134. return $columns;
  135. }
  136. /**
  137. * 创建
  138. * @param array $data
  139. * @return mixed
  140. * @author 等风来
  141. * @email 136327134@qq.com
  142. * @date 2023/4/11
  143. */
  144. public function createCrud(array $data)
  145. {
  146. $tableName = $data['tableName'];
  147. $tableComment = $data['tableComment'];
  148. $tableField = $data['tableField'];
  149. $filePath = $data['filePath'];
  150. //创建数据库
  151. if ($tableField && !$data['isTable']) {
  152. $this->makeDatebase($tableName, $tableComment, $tableField);
  153. }
  154. if (in_array($tableName, self::NOT_CRUD_TABANAME)) {
  155. throw new ValidateException('不能生成系统自带数据表');
  156. }
  157. //读取表结构
  158. $column = $this->getColumnNamesList($tableName);
  159. if (!$column) {
  160. throw new ValidateException('请先创建' . $tableName . '表');
  161. }
  162. $routeName = 'crud/' . Str::snake($tableName);
  163. $uniqueAuth = $routeName . '-index-list';
  164. foreach ($filePath as $k => $i) {
  165. if (in_array($k, ['pages', 'router', 'api'])) {
  166. $filePath[$k] = Make::adminTemplatePath() . $i;
  167. } else {
  168. $filePath[$k] = app()->getRootPath() . $i;
  169. }
  170. }
  171. //创建菜单
  172. if (!$data['menuName']) {
  173. $data['menuName'] = $tableName;
  174. }
  175. $dataMenu = [
  176. 'pid' => $data['pid'],
  177. 'menu_name' => $data['menuName'],
  178. 'menu_path' => '',
  179. 'auth_type' => 1,
  180. 'is_show' => 1,
  181. 'is_del' => 0,
  182. 'unique_auth' => $uniqueAuth,
  183. 'is_header' => $data['pid'] ? 0 : 1,
  184. ];
  185. $res = $this->transaction(function () use ($filePath, $tableName, $routeName, $data, $dataMenu) {
  186. $menuInfo = app()->make(SystemMenusServices::class)->save($dataMenu);
  187. //写入路由权限
  188. $cateId = app()->make(SystemRouteServices::class)->topCateId('adminapi');
  189. $ruleData = [
  190. [
  191. 'path' => $routeName,
  192. 'method' => 'GET',
  193. 'name' => $data['menuName'] . '列表接口',
  194. 'app_name' => 'adminapi',
  195. 'cate_id' => $cateId,
  196. 'add_time' => date('Y-m-d H:i:s')
  197. ],
  198. [
  199. 'path' => $routeName . '/create',
  200. 'method' => 'GET',
  201. 'name' => $data['menuName'] . '获取创建表单接口',
  202. 'app_name' => 'adminapi',
  203. 'cate_id' => $cateId,
  204. 'add_time' => date('Y-m-d H:i:s')
  205. ],
  206. [
  207. 'path' => $routeName,
  208. 'method' => 'POST',
  209. 'name' => $data['menuName'] . '保存数据接口',
  210. 'app_name' => 'adminapi',
  211. 'cate_id' => $cateId,
  212. 'add_time' => date('Y-m-d H:i:s')
  213. ],
  214. [
  215. 'path' => $routeName . '/<id>/edit',
  216. 'method' => 'GET',
  217. 'name' => $data['menuName'] . '获取修改表单接口',
  218. 'app_name' => 'adminapi',
  219. 'cate_id' => $cateId,
  220. 'add_time' => date('Y-m-d H:i:s')
  221. ],
  222. [
  223. 'path' => $routeName . '/<id>',
  224. 'method' => 'PUT',
  225. 'name' => $data['menuName'] . '修改数据接口',
  226. 'app_name' => 'adminapi',
  227. 'cate_id' => $cateId,
  228. 'add_time' => date('Y-m-d H:i:s')
  229. ],
  230. [
  231. 'path' => $routeName . '/<id>',
  232. 'method' => 'DELETE',
  233. 'name' => $data['menuName'] . '删除数据接口',
  234. 'app_name' => 'adminapi',
  235. 'cate_id' => $cateId,
  236. 'add_time' => date('Y-m-d H:i:s')
  237. ],
  238. ];
  239. app()->make(SystemRouteServices::class)->saveAll($ruleData);
  240. //记录权限加入菜单表
  241. $menuData = [];
  242. foreach ($ruleData as $item) {
  243. $menuData[] = [
  244. 'pid' => $menuInfo->id,
  245. 'method' => $item['method'],
  246. 'api_url' => $item['path'],
  247. 'name' => $item['name'],
  248. 'is_del' => 0,
  249. ];
  250. }
  251. app()->make(SystemMenusServices::class)->saveAll($menuData);
  252. $make = $this->makeFile($tableName, $routeName, true, $data, $filePath);
  253. $makePath = [];
  254. foreach ($make as $key => $item) {
  255. $makePath[$key] = $item['path'];
  256. }
  257. //记录crud生成
  258. $res = $this->dao->save([
  259. 'pid' => $data['pid'],
  260. 'name' => $data['menuName'],
  261. 'table_name' => $tableName,
  262. 'field' => json_encode($data),
  263. 'make_path' => json_encode($makePath),
  264. 'add_time' => time()
  265. ]);
  266. return $res;
  267. });
  268. return $res->toArray();
  269. }
  270. /**
  271. * 创建数据库
  272. * @param string $tableName
  273. * @param string $tableComment
  274. * @param array $tableField
  275. * @author 等风来
  276. * @email 136327134@qq.com
  277. * @date 2023/4/7
  278. */
  279. public function makeDatebase(string $tableName, string $tableComment, array $tableField = [])
  280. {
  281. $migrator = app()->make(Migrator::class);
  282. //创建表
  283. $table = $migrator->table($tableName, $tableComment);
  284. //创建字段
  285. foreach ($tableField as $item) {
  286. $option = [];
  287. if (!isset($item['limit'])) {
  288. $option['limit'] = (int)$item['limit'];
  289. }
  290. if (!isset($item['default'])) {
  291. $option['default'] = $item['default'];
  292. }
  293. $option['comment'] = $item['comment'];
  294. $table->addColumn($item['field'], $item['type'], $option);
  295. }
  296. //创建修改和增加时间
  297. if (!empty($data['tableTime'])) {
  298. $table->addTimestamps();
  299. }
  300. //创建索引
  301. if (!empty($data['tableIndex'])) {
  302. foreach ($data['tableIndex'] as $item) {
  303. $table->addIndex($item);
  304. }
  305. }
  306. //创建伪删除
  307. if (!empty($data['tableDelete'])) {
  308. $table->addSoftDelete();
  309. }
  310. //执行创建
  311. $table->create();
  312. }
  313. /**
  314. * 创建文件返回文件路径和内容
  315. * @param string $tableName
  316. * @param string $routeName
  317. * @param bool $isMake
  318. * @param array $options
  319. * @param array $filePath
  320. * @return array[]
  321. * @author 等风来
  322. * @email 136327134@qq.com
  323. * @date 2023/4/7
  324. */
  325. public function makeFile(string $tableName, string $routeName, bool $isMake = false, array $options = [], array $filePath = [])
  326. {
  327. $options['fromField'] = is_array($options['fromField']) ? $options['fromField'] : [];
  328. $options['columnField'] = is_array($options['columnField']) ? $options['columnField'] : [];
  329. //生成控制器
  330. $controller = app()->make(Controller::class);
  331. [$controllerContent, $controllerPath] = $controller->setFilePathName($filePath['controller'] ?? '')->isMake($isMake)->handle($tableName);
  332. //生成模型
  333. $model = app()->make(Model::class);
  334. [$modelContent, $modelPath] = $model->setFilePathName($filePath['model'] ?? '')->isMake($isMake)->handle($tableName);
  335. //生成dao
  336. $dao = app()->make(Dao::class);
  337. [$daoContent, $daoPath] = $dao->setFilePathName($filePath['dao'] ?? '')->isMake($isMake)->handle($tableName);
  338. //生成路由
  339. $route = app()->make(Route::class);
  340. [$routeContent, $routePath] = $route->setFilePathName($filePath['route'] ?? '')->isMake($isMake)->handle($tableName, [
  341. 'menus' => $options['menuName'],
  342. 'route' => $routeName
  343. ]);
  344. //生成service
  345. $service = app()->make(Service::class);
  346. [$serviceContent, $servicePath] = $service->setFilePathName($filePath['service'] ?? '')->isMake($isMake)->handle($tableName, [
  347. 'field' => $options['fromField'],
  348. ]);
  349. //生成验证器
  350. $validate = app()->make(Validate::class);
  351. [$validateContent, $validatePath] = $validate->setFilePathName($filePath['validate'] ?? '')->isMake($isMake)->handle($tableName);
  352. //生成前台路由
  353. $viewRouter = app()->make(ViewRouter::class);
  354. [$routerContent, $routerPath] = $viewRouter->setFilePathName($filePath['router'] ?? '')->isMake($isMake)->handle($tableName, [
  355. 'route' => $routeName,
  356. ]);
  357. //生成前台接口
  358. $viewApi = app()->make(ViewApi::class);
  359. [$apiContent, $apiPath] = $viewApi->setFilePathName($filePath['api'] ?? '')->isMake($isMake)->handle($tableName, [
  360. 'route' => $routeName,
  361. ]);
  362. //生成前台页面
  363. $viewPages = app()->make(ViewPages::class);
  364. [$pagesContent, $pagesPath] = $viewPages->setFilePathName($filePath['pages'] ?? '')->isMake($isMake)->handle($tableName, [
  365. 'field' => $options['columnField']
  366. ]);
  367. return [
  368. 'controller' => [
  369. 'path' => $this->replace($controllerPath),
  370. 'content' => $controllerContent
  371. ],
  372. 'model' => [
  373. 'path' => $this->replace($modelPath),
  374. 'content' => $modelContent
  375. ],
  376. 'dao' => [
  377. 'path' => $this->replace($daoPath),
  378. 'content' => $daoContent
  379. ],
  380. 'route' => [
  381. 'path' => $this->replace($routePath),
  382. 'content' => $routeContent
  383. ],
  384. 'service' => [
  385. 'path' => $this->replace($servicePath),
  386. 'content' => $serviceContent
  387. ],
  388. 'validate' => [
  389. 'path' => $this->replace($validatePath),
  390. 'content' => $validateContent
  391. ],
  392. 'router' => [
  393. 'path' => $this->replace($routerPath),
  394. 'content' => $routerContent
  395. ],
  396. 'api' => [
  397. 'path' => $this->replace($apiPath),
  398. 'content' => $apiContent
  399. ],
  400. 'pages' => [
  401. 'path' => $this->replace($pagesPath),
  402. 'content' => $pagesContent
  403. ],
  404. ];
  405. }
  406. protected function replace(string $path)
  407. {
  408. return str_replace([app()->getRootPath(), Make::adminTemplatePath()], '', $path);
  409. }
  410. /**
  411. * @param string $tableName
  412. * @param bool $fullName
  413. * @return string
  414. * @author 等风来
  415. * @email 136327134@qq.com
  416. * @date 2023/4/7
  417. */
  418. public function getTableName(string $tableName, bool $fullName = true)
  419. {
  420. $tablePrefix = config('database.connections.mysql.prefix');
  421. $pattern = '/^' . $tablePrefix . '/i';
  422. return ($fullName ? $tablePrefix : '') . (preg_replace($pattern, '', $tableName));
  423. }
  424. }