SystemCrudServices.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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. * @param array $data
  138. * @return array
  139. * @author 等风来
  140. * @email 136327134@qq.com
  141. * @date 2023/4/12
  142. */
  143. public function valueReplace(array $data)
  144. {
  145. $replace = ['phar://'];
  146. $newData = [];
  147. foreach ($data as $key => $item) {
  148. if (is_array($item)) {
  149. $item = $this->valueReplace($item);
  150. } else {
  151. $item = str_replace($replace, '', $item);
  152. }
  153. $newData[str_replace($replace, '', $key)] = $item;
  154. }
  155. return $newData;
  156. }
  157. /**
  158. * 创建
  159. * @param array $data
  160. * @return mixed
  161. * @author 等风来
  162. * @email 136327134@qq.com
  163. * @date 2023/4/11
  164. */
  165. public function createCrud(array $data)
  166. {
  167. $tableName = $data['tableName'];
  168. $tableComment = $data['tableComment'];
  169. $tableField = $this->valueReplace($data['tableField']);
  170. $filePath = $this->valueReplace($data['filePath']);
  171. //创建数据库
  172. if ($tableField && !$data['isTable']) {
  173. $this->makeDatebase($tableName, $tableComment, $tableField);
  174. }
  175. if (in_array($tableName, self::NOT_CRUD_TABANAME)) {
  176. throw new ValidateException('不能生成系统自带数据表');
  177. }
  178. //读取表结构
  179. $column = $this->getColumnNamesList($tableName);
  180. if (!$column) {
  181. throw new ValidateException('请先创建' . $tableName . '表');
  182. }
  183. foreach ($column as $value) {
  184. if ($value['primaryKey']) {
  185. $data['key'] = $value['name'];
  186. break;
  187. }
  188. }
  189. $routeName = 'crud/' . Str::snake($tableName);
  190. $uniqueAuth = Str::snake($tableName) . '-crud-list-index';
  191. foreach ($filePath as $k => $i) {
  192. if (in_array($k, ['pages', 'router', 'api'])) {
  193. $filePath[$k] = Make::adminTemplatePath() . $i;
  194. } else {
  195. $filePath[$k] = app()->getRootPath() . $i;
  196. }
  197. }
  198. //创建菜单
  199. if (!$data['menuName']) {
  200. $data['menuName'] = $tableName;
  201. }
  202. $dataMenu = [
  203. 'pid' => $data['pid'],
  204. 'menu_name' => $data['menuName'],
  205. 'menu_path' => '',
  206. 'auth_type' => 1,
  207. 'is_show' => 1,
  208. 'is_del' => 0,
  209. 'unique_auth' => $uniqueAuth,
  210. 'is_header' => $data['pid'] ? 0 : 1,
  211. ];
  212. $res = $this->transaction(function () use ($filePath, $tableName, $routeName, $data, $dataMenu) {
  213. $menuInfo = app()->make(SystemMenusServices::class)->save($dataMenu);
  214. //写入路由权限
  215. $cateId = app()->make(SystemRouteServices::class)->topCateId('adminapi');
  216. $ruleData = [
  217. [
  218. 'path' => $routeName,
  219. 'method' => 'GET',
  220. 'name' => $data['menuName'] . '列表接口',
  221. 'app_name' => 'adminapi',
  222. 'cate_id' => $cateId,
  223. 'add_time' => date('Y-m-d H:i:s')
  224. ],
  225. [
  226. 'path' => $routeName . '/create',
  227. 'method' => 'GET',
  228. 'name' => $data['menuName'] . '获取创建表单接口',
  229. 'app_name' => 'adminapi',
  230. 'cate_id' => $cateId,
  231. 'add_time' => date('Y-m-d H:i:s')
  232. ],
  233. [
  234. 'path' => $routeName,
  235. 'method' => 'POST',
  236. 'name' => $data['menuName'] . '保存数据接口',
  237. 'app_name' => 'adminapi',
  238. 'cate_id' => $cateId,
  239. 'add_time' => date('Y-m-d H:i:s')
  240. ],
  241. [
  242. 'path' => $routeName . '/<id>/edit',
  243. 'method' => 'GET',
  244. 'name' => $data['menuName'] . '获取修改表单接口',
  245. 'app_name' => 'adminapi',
  246. 'cate_id' => $cateId,
  247. 'add_time' => date('Y-m-d H:i:s')
  248. ],
  249. [
  250. 'path' => $routeName . '/<id>',
  251. 'method' => 'PUT',
  252. 'name' => $data['menuName'] . '修改数据接口',
  253. 'app_name' => 'adminapi',
  254. 'cate_id' => $cateId,
  255. 'add_time' => date('Y-m-d H:i:s')
  256. ],
  257. [
  258. 'path' => $routeName . '/<id>',
  259. 'method' => 'DELETE',
  260. 'name' => $data['menuName'] . '删除数据接口',
  261. 'app_name' => 'adminapi',
  262. 'cate_id' => $cateId,
  263. 'add_time' => date('Y-m-d H:i:s')
  264. ],
  265. ];
  266. app()->make(SystemRouteServices::class)->saveAll($ruleData);
  267. //记录权限加入菜单表
  268. $menuData = [];
  269. foreach ($ruleData as $item) {
  270. $menuData[] = [
  271. 'pid' => $menuInfo->id,
  272. 'methods' => $item['method'],
  273. 'api_url' => $item['path'],
  274. 'name' => $item['name'],
  275. 'is_del' => 0,
  276. ];
  277. }
  278. app()->make(SystemMenusServices::class)->saveAll($menuData);
  279. $make = $this->makeFile($tableName, $routeName, true, $data, $filePath);
  280. $makePath = [];
  281. foreach ($make as $key => $item) {
  282. $makePath[$key] = $item['path'];
  283. }
  284. //记录crud生成
  285. $res = $this->dao->save([
  286. 'pid' => $data['pid'],
  287. 'name' => $data['menuName'],
  288. 'table_name' => $tableName,
  289. 'field' => json_encode($data),
  290. 'make_path' => json_encode($makePath),
  291. 'add_time' => time()
  292. ]);
  293. return $res;
  294. });
  295. return $res->toArray();
  296. }
  297. /**
  298. * 创建数据库
  299. * @param string $tableName
  300. * @param string $tableComment
  301. * @param array $tableField
  302. * @author 等风来
  303. * @email 136327134@qq.com
  304. * @date 2023/4/7
  305. */
  306. public function makeDatebase(string $tableName, string $tableComment, array $tableField = [])
  307. {
  308. $migrator = app()->make(Migrator::class);
  309. //创建表
  310. $table = $migrator->table($tableName, $tableComment);
  311. //创建字段
  312. foreach ($tableField as $item) {
  313. $option = [];
  314. if (!isset($item['limit'])) {
  315. $option['limit'] = (int)$item['limit'];
  316. }
  317. if (!isset($item['default'])) {
  318. $option['default'] = $item['default'];
  319. }
  320. $option['comment'] = $item['comment'];
  321. $table->addColumn($item['field'], $item['type'], $option);
  322. }
  323. //创建修改和增加时间
  324. if (!empty($data['tableTime'])) {
  325. $table->addTimestamps();
  326. }
  327. //创建索引
  328. if (!empty($data['tableIndex'])) {
  329. foreach ($data['tableIndex'] as $item) {
  330. $table->addIndex($item);
  331. }
  332. }
  333. //创建伪删除
  334. if (!empty($data['tableDelete'])) {
  335. $table->addSoftDelete();
  336. }
  337. //执行创建
  338. $table->create();
  339. }
  340. /**
  341. * 创建文件返回文件路径和内容
  342. * @param string $tableName
  343. * @param string $routeName
  344. * @param bool $isMake
  345. * @param array $options
  346. * @param array $filePath
  347. * @return array[]
  348. * @author 等风来
  349. * @email 136327134@qq.com
  350. * @date 2023/4/7
  351. */
  352. public function makeFile(string $tableName, string $routeName, bool $isMake = false, array $options = [], array $filePath = [])
  353. {
  354. $options['fromField'] = is_array($options['fromField']) ? $options['fromField'] : [];
  355. $options['columnField'] = is_array($options['columnField']) ? $options['columnField'] : [];
  356. //生成模型
  357. $model = app()->make(Model::class);
  358. [$modelContent, $modelPath, $usePath] = $model->setFilePathName($filePath['model'] ?? '')->isMake($isMake)->handle($tableName);
  359. //生成dao
  360. $dao = app()->make(Dao::class);
  361. [$daoContent, $daoPath, $usePath] = $dao->setFilePathName($filePath['dao'] ?? '')->isMake($isMake)->handle($tableName, [
  362. 'usePath' => $usePath,
  363. ]);
  364. //生成service
  365. $service = app()->make(Service::class);
  366. [$serviceContent, $servicePath, $usePath] = $service->setFilePathName($filePath['service'] ?? '')->isMake($isMake)->handle($tableName, [
  367. 'field' => $options['fromField'],
  368. 'usePath' => $usePath,
  369. ]);
  370. //生成验证器
  371. $validate = app()->make(Validate::class);
  372. [$validateContent, $validatePath] = $validate->setFilePathName($filePath['validate'] ?? '')->isMake($isMake)->handle($tableName);
  373. //生成控制器
  374. $controller = app()->make(Controller::class);
  375. [$controllerContent, $controllerPath] = $controller->setFilePathName($filePath['controller'] ?? '')->isMake($isMake)->handle($tableName, [
  376. 'usePath' => $usePath
  377. ]);
  378. //生成路由
  379. $route = app()->make(Route::class);
  380. [$routeContent, $routePath] = $route->setFilePathName($filePath['route'] ?? '')->isMake($isMake)->handle($tableName, [
  381. 'menus' => $options['menuName'],
  382. 'route' => $routeName
  383. ]);
  384. //生成前台路由
  385. $viewRouter = app()->make(ViewRouter::class);
  386. [$routerContent, $routerPath] = $viewRouter->setFilePathName($filePath['router'] ?? '')->isMake($isMake)->handle($tableName, [
  387. 'route' => $routeName,
  388. ]);
  389. //生成前台接口
  390. $viewApi = app()->make(ViewApi::class);
  391. [$apiContent, $apiPath] = $viewApi->setFilePathName($filePath['api'] ?? '')->isMake($isMake)->handle($tableName, [
  392. 'route' => $routeName,
  393. ]);
  394. //生成前台页面
  395. $viewPages = app()->make(ViewPages::class);
  396. [$pagesContent, $pagesPath] = $viewPages->setFilePathName($filePath['pages'] ?? '')->isMake($isMake)->handle($tableName, [
  397. 'field' => $options['columnField'],
  398. 'pathApiJs' => '@/' . str_replace('\\', '/', str_replace([Make::adminTemplatePath(), '.js'], '', $apiPath)),
  399. ]);
  400. return [
  401. 'controller' => [
  402. 'path' => $this->replace($controllerPath),
  403. 'content' => $controllerContent
  404. ],
  405. 'model' => [
  406. 'path' => $this->replace($modelPath),
  407. 'content' => $modelContent
  408. ],
  409. 'dao' => [
  410. 'path' => $this->replace($daoPath),
  411. 'content' => $daoContent
  412. ],
  413. 'route' => [
  414. 'path' => $this->replace($routePath),
  415. 'content' => $routeContent
  416. ],
  417. 'service' => [
  418. 'path' => $this->replace($servicePath),
  419. 'content' => $serviceContent
  420. ],
  421. 'validate' => [
  422. 'path' => $this->replace($validatePath),
  423. 'content' => $validateContent
  424. ],
  425. 'router' => [
  426. 'path' => $this->replace($routerPath),
  427. 'content' => $routerContent
  428. ],
  429. 'api' => [
  430. 'path' => $this->replace($apiPath),
  431. 'content' => $apiContent
  432. ],
  433. 'pages' => [
  434. 'path' => $this->replace($pagesPath),
  435. 'content' => $pagesContent
  436. ],
  437. ];
  438. }
  439. protected function replace(string $path)
  440. {
  441. return str_replace([app()->getRootPath(), Make::adminTemplatePath()], '', $path);
  442. }
  443. /**
  444. * @param string $tableName
  445. * @param bool $fullName
  446. * @return string
  447. * @author 等风来
  448. * @email 136327134@qq.com
  449. * @date 2023/4/7
  450. */
  451. public function getTableName(string $tableName, bool $fullName = true)
  452. {
  453. $tablePrefix = config('database.connections.mysql.prefix');
  454. $pattern = '/^' . $tablePrefix . '/i';
  455. return ($fullName ? $tablePrefix : '') . (preg_replace($pattern, '', $tableName));
  456. }
  457. }