SystemCrudServices.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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. $rule = [
  82. 'varchat' => 'string',
  83. 'int' => 'integer',
  84. 'biginteger' => 'bigint',
  85. ];
  86. return [
  87. 'types' => [
  88. 'varchar',
  89. 'char',
  90. 'text',
  91. 'longtext',
  92. 'tinytext',
  93. 'enum',
  94. 'blob',
  95. 'binary',
  96. 'varbinary',
  97. 'datetime',
  98. 'timestamp',
  99. 'time',
  100. 'date',
  101. 'year',
  102. 'boolean',
  103. 'tinyint',
  104. 'int',
  105. 'decimal',
  106. 'float',
  107. 'json',
  108. 'addTimestamps',
  109. 'addSoftDelete',
  110. ],
  111. 'rule' => $rule
  112. ];
  113. }
  114. /**
  115. * 改变数据库类型
  116. * @param string $type
  117. * @return string
  118. * @author 等风来
  119. * @email 136327134@qq.com
  120. * @date 2023/4/13
  121. */
  122. public function changeTabelRule(string $type)
  123. {
  124. if (!in_array($type, $this->getTabelRule()['type'])) {
  125. throw new ValidateException('类型不在支持范围');
  126. }
  127. return $this->getTabelRule()['rule'][$type] ?? $type;
  128. }
  129. /**
  130. * 获取表字段
  131. * @param string $tableName
  132. * @return mixed
  133. * @author 等风来
  134. * @email 136327134@qq.com
  135. * @date 2023/4/7
  136. */
  137. public function getColumnNamesList(string $tableName)
  138. {
  139. $sql = 'SELECT * FROM `information_schema`.`columns` WHERE TABLE_SCHEMA = ? AND table_name = ? ORDER BY ORDINAL_POSITION';
  140. $column = Db::query($sql, [config('database.connections.mysql.database'), $this->getTableName($tableName)]);
  141. $columns = [];
  142. foreach ($column as $item) {
  143. $column = [
  144. 'name' => $item['COLUMN_NAME'],
  145. 'type' => $item['DATA_TYPE'],
  146. 'dataType' => stripos($item['COLUMN_TYPE'], '(') !== false ? substr_replace($item['COLUMN_TYPE'], '', stripos($item['COLUMN_TYPE'], ')') + 1) : $item['COLUMN_TYPE'],
  147. 'default' => $item['COLUMN_DEFAULT'],
  148. 'null' => $item['IS_NULLABLE'] == 'YES',
  149. 'primaryKey' => $item['COLUMN_KEY'] == 'PRI',
  150. 'unsigned' => (bool)stripos($item['COLUMN_TYPE'], 'unsigned'),
  151. 'autoIncrement' => stripos($item['EXTRA'], 'auto_increment') !== false,
  152. 'comment' => $item['COLUMN_COMMENT'],
  153. 'limit' => $item['CHARACTER_MAXIMUM_LENGTH'] ?: $item['NUMERIC_PRECISION'],
  154. ];
  155. $columns[$item['COLUMN_NAME']] = $column;
  156. }
  157. return $columns;
  158. }
  159. /**
  160. * @param array $data
  161. * @return array
  162. * @author 等风来
  163. * @email 136327134@qq.com
  164. * @date 2023/4/12
  165. */
  166. public function valueReplace(array $data)
  167. {
  168. $replace = ['phar://'];
  169. $newData = [];
  170. foreach ($data as $key => $item) {
  171. if (is_array($item)) {
  172. $item = $this->valueReplace($item);
  173. } else {
  174. $item = str_replace($replace, '', $item);
  175. }
  176. $newData[str_replace($replace, '', $key)] = $item;
  177. }
  178. return $newData;
  179. }
  180. /**
  181. * 创建
  182. * @param array $data
  183. * @return mixed
  184. * @author 等风来
  185. * @email 136327134@qq.com
  186. * @date 2023/4/11
  187. */
  188. public function createCrud(array $data)
  189. {
  190. $tableName = $data['tableName'];
  191. $tableComment = $data['tableComment'];
  192. $tableField = $this->valueReplace($data['tableField']);
  193. $filePath = $this->valueReplace($data['filePath']);
  194. //创建数据库
  195. if ($tableField && !$data['isTable']) {
  196. $this->makeDatebase($tableName, $tableComment, $tableField);
  197. }
  198. if (in_array($tableName, self::NOT_CRUD_TABANAME)) {
  199. throw new ValidateException('不能生成系统自带数据表');
  200. }
  201. //读取表结构
  202. $column = $this->getColumnNamesList($tableName);
  203. if (!$column) {
  204. throw new ValidateException('请先创建' . $tableName . '表');
  205. }
  206. //获取主键
  207. foreach ($column as $value) {
  208. if ($value['primaryKey']) {
  209. $data['key'] = $value['name'];
  210. break;
  211. }
  212. }
  213. $routeName = 'crud/' . Str::snake($tableName);
  214. $uniqueAuth = Str::snake($tableName) . '-crud-list-index';
  215. //增加保存的绝对路径
  216. foreach ($filePath as $k => $i) {
  217. if (in_array($k, ['pages', 'router', 'api'])) {
  218. $filePath[$k] = Make::adminTemplatePath() . $i;
  219. } else {
  220. $filePath[$k] = app()->getRootPath() . $i;
  221. }
  222. }
  223. //创建菜单
  224. if (!$data['menuName']) {
  225. $data['menuName'] = $tableName;
  226. }
  227. $dataMenu = [
  228. 'pid' => $data['pid'],
  229. 'menu_name' => $data['menuName'],
  230. 'menu_path' => '',
  231. 'auth_type' => 1,
  232. 'is_show' => 1,
  233. 'is_del' => 0,
  234. 'unique_auth' => $uniqueAuth,
  235. 'is_header' => $data['pid'] ? 0 : 1,
  236. ];
  237. $res = $this->transaction(function () use ($filePath, $tableName, $routeName, $data, $dataMenu) {
  238. $menuInfo = app()->make(SystemMenusServices::class)->save($dataMenu);
  239. //写入路由权限
  240. $cateId = app()->make(SystemRouteServices::class)->topCateId('adminapi');
  241. $ruleData = [
  242. [
  243. 'path' => $routeName,
  244. 'method' => 'GET',
  245. 'name' => $data['menuName'] . '列表接口',
  246. 'app_name' => 'adminapi',
  247. 'cate_id' => $cateId,
  248. 'add_time' => date('Y-m-d H:i:s')
  249. ],
  250. [
  251. 'path' => $routeName . '/create',
  252. 'method' => 'GET',
  253. 'name' => $data['menuName'] . '获取创建表单接口',
  254. 'app_name' => 'adminapi',
  255. 'cate_id' => $cateId,
  256. 'add_time' => date('Y-m-d H:i:s')
  257. ],
  258. [
  259. 'path' => $routeName,
  260. 'method' => 'POST',
  261. 'name' => $data['menuName'] . '保存数据接口',
  262. 'app_name' => 'adminapi',
  263. 'cate_id' => $cateId,
  264. 'add_time' => date('Y-m-d H:i:s')
  265. ],
  266. [
  267. 'path' => $routeName . '/<id>/edit',
  268. 'method' => 'GET',
  269. 'name' => $data['menuName'] . '获取修改表单接口',
  270. 'app_name' => 'adminapi',
  271. 'cate_id' => $cateId,
  272. 'add_time' => date('Y-m-d H:i:s')
  273. ],
  274. [
  275. 'path' => $routeName . '/<id>',
  276. 'method' => 'PUT',
  277. 'name' => $data['menuName'] . '修改数据接口',
  278. 'app_name' => 'adminapi',
  279. 'cate_id' => $cateId,
  280. 'add_time' => date('Y-m-d H:i:s')
  281. ],
  282. [
  283. 'path' => $routeName . '/<id>',
  284. 'method' => 'DELETE',
  285. 'name' => $data['menuName'] . '删除数据接口',
  286. 'app_name' => 'adminapi',
  287. 'cate_id' => $cateId,
  288. 'add_time' => date('Y-m-d H:i:s')
  289. ],
  290. ];
  291. app()->make(SystemRouteServices::class)->saveAll($ruleData);
  292. //记录权限加入菜单表
  293. $menuData = [];
  294. foreach ($ruleData as $item) {
  295. $menuData[] = [
  296. 'pid' => $menuInfo->id,
  297. 'methods' => $item['method'],
  298. 'api_url' => $item['path'],
  299. 'name' => $item['name'],
  300. 'is_del' => 0,
  301. ];
  302. }
  303. app()->make(SystemMenusServices::class)->saveAll($menuData);
  304. //生成文件
  305. $make = $this->makeFile($tableName, $routeName, true, $data, $filePath);
  306. $makePath = [];
  307. foreach ($make as $key => $item) {
  308. $makePath[$key] = $item['path'];
  309. }
  310. //记录crud生成
  311. $res = $this->dao->save([
  312. 'pid' => $data['pid'],
  313. 'name' => $data['menuName'],
  314. 'table_name' => $tableName,
  315. 'field' => json_encode($data),
  316. 'make_path' => json_encode($makePath),
  317. 'add_time' => time()
  318. ]);
  319. return $res;
  320. });
  321. return $res->toArray();
  322. }
  323. /**
  324. * 创建数据库
  325. * @param string $tableName
  326. * @param string $tableComment
  327. * @param array $tableField
  328. * @author 等风来
  329. * @email 136327134@qq.com
  330. * @date 2023/4/7
  331. */
  332. public function makeDatebase(string $tableName, string $tableComment, array $tableField = [])
  333. {
  334. $migrator = app()->make(Migrator::class, [date('YmdHis')]);
  335. //创建表
  336. $table = $migrator->table($tableName, $tableComment);
  337. //创建字段
  338. foreach ($tableField as $item) {
  339. $option = [];
  340. if (!isset($item['limit'])) {
  341. $option['limit'] = (int)$item['limit'];
  342. }
  343. if (!isset($item['default'])) {
  344. $option['default'] = $item['default'];
  345. }
  346. //创建伪删除
  347. if ($item['type'] === 'addSoftDelete') {
  348. $table->addSoftDelete();
  349. } else if ($item['type'] === 'addTimestamps') {
  350. //创建修改和增加时间
  351. $table->addTimestamps();
  352. } else {
  353. $option['comment'] = $item['comment'];
  354. $table->addColumn($item['field'], $this->changeTabelRule($item['type']), $option);
  355. }
  356. }
  357. //创建索引
  358. if (!empty($data['tableIndex'])) {
  359. foreach ($data['tableIndex'] as $item) {
  360. $table->addIndex($item);
  361. }
  362. }
  363. //执行创建
  364. $table->create();
  365. }
  366. /**
  367. * 创建文件返回文件路径和内容
  368. * @param string $tableName
  369. * @param string $routeName
  370. * @param bool $isMake
  371. * @param array $options
  372. * @param array $filePath
  373. * @return array[]
  374. * @author 等风来
  375. * @email 136327134@qq.com
  376. * @date 2023/4/7
  377. */
  378. public function makeFile(string $tableName, string $routeName, bool $isMake = false, array $options = [], array $filePath = [])
  379. {
  380. $options['fromField'] = is_array($options['fromField']) ? $options['fromField'] : [];
  381. $options['columnField'] = is_array($options['columnField']) ? $options['columnField'] : [];
  382. //生成模型
  383. $model = app()->make(Model::class);
  384. [$modelContent, $modelPath, $usePath] = $model->setFilePathName($filePath['model'] ?? '')->isMake($isMake)->handle($tableName, $options);
  385. //生成dao
  386. $dao = app()->make(Dao::class);
  387. [$daoContent, $daoPath, $usePath] = $dao->setFilePathName($filePath['dao'] ?? '')->isMake($isMake)->handle($tableName, [
  388. 'usePath' => $usePath,
  389. ]);
  390. //生成service
  391. $service = app()->make(Service::class);
  392. [$serviceContent, $servicePath, $usePath] = $service->setFilePathName($filePath['service'] ?? '')->isMake($isMake)->handle($tableName, [
  393. 'field' => $options['fromField'],
  394. 'usePath' => $usePath,
  395. ]);
  396. //生成验证器
  397. $validate = app()->make(Validate::class);
  398. [$validateContent, $validatePath] = $validate->setFilePathName($filePath['validate'] ?? '')->isMake($isMake)->handle($tableName);
  399. //生成控制器
  400. $controller = app()->make(Controller::class);
  401. [$controllerContent, $controllerPath] = $controller->setFilePathName($filePath['controller'] ?? '')->isMake($isMake)->handle($tableName, [
  402. 'usePath' => $usePath
  403. ]);
  404. //生成路由
  405. $route = app()->make(Route::class);
  406. [$routeContent, $routePath] = $route->setFilePathName($filePath['route'] ?? '')->isMake($isMake)->handle($tableName, [
  407. 'menus' => $options['menuName'],
  408. 'route' => $routeName
  409. ]);
  410. //生成前台路由
  411. $viewRouter = app()->make(ViewRouter::class);
  412. [$routerContent, $routerPath] = $viewRouter->setFilePathName($filePath['router'] ?? '')->isMake($isMake)->handle($tableName, [
  413. 'route' => $routeName,
  414. ]);
  415. //生成前台接口
  416. $viewApi = app()->make(ViewApi::class);
  417. [$apiContent, $apiPath] = $viewApi->setFilePathName($filePath['api'] ?? '')->isMake($isMake)->handle($tableName, [
  418. 'route' => $routeName,
  419. ]);
  420. //生成前台页面
  421. $viewPages = app()->make(ViewPages::class);
  422. [$pagesContent, $pagesPath] = $viewPages->setFilePathName($filePath['pages'] ?? '')->isMake($isMake)->handle($tableName, [
  423. 'field' => $options['columnField'],
  424. 'pathApiJs' => '@/' . str_replace('\\', '/', str_replace([Make::adminTemplatePath(), '.js'], '', $apiPath)),
  425. ]);
  426. return [
  427. 'controller' => [
  428. 'path' => $this->replace($controllerPath),
  429. 'content' => $controllerContent
  430. ],
  431. 'model' => [
  432. 'path' => $this->replace($modelPath),
  433. 'content' => $modelContent
  434. ],
  435. 'dao' => [
  436. 'path' => $this->replace($daoPath),
  437. 'content' => $daoContent
  438. ],
  439. 'route' => [
  440. 'path' => $this->replace($routePath),
  441. 'content' => $routeContent
  442. ],
  443. 'service' => [
  444. 'path' => $this->replace($servicePath),
  445. 'content' => $serviceContent
  446. ],
  447. 'validate' => [
  448. 'path' => $this->replace($validatePath),
  449. 'content' => $validateContent
  450. ],
  451. 'router' => [
  452. 'path' => $this->replace($routerPath),
  453. 'content' => $routerContent
  454. ],
  455. 'api' => [
  456. 'path' => $this->replace($apiPath),
  457. 'content' => $apiContent
  458. ],
  459. 'pages' => [
  460. 'path' => $this->replace($pagesPath),
  461. 'content' => $pagesContent
  462. ],
  463. ];
  464. }
  465. protected function replace(string $path)
  466. {
  467. return str_replace([app()->getRootPath(), Make::adminTemplatePath()], '', $path);
  468. }
  469. /**
  470. * @param string $tableName
  471. * @param bool $fullName
  472. * @return string
  473. * @author 等风来
  474. * @email 136327134@qq.com
  475. * @date 2023/4/7
  476. */
  477. public function getTableName(string $tableName, bool $fullName = true)
  478. {
  479. $tablePrefix = config('database.connections.mysql.prefix');
  480. $pattern = '/^' . $tablePrefix . '/i';
  481. return ($fullName ? $tablePrefix : '') . (preg_replace($pattern, '', $tableName));
  482. }
  483. }