SystemCrudServices.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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\exceptions\AdminException;
  17. use crmeb\services\crud\Controller;
  18. use crmeb\services\crud\Dao;
  19. use crmeb\services\crud\Make;
  20. use crmeb\services\crud\Model;
  21. use crmeb\services\crud\Route;
  22. use crmeb\services\crud\Service;
  23. use crmeb\services\crud\Validate;
  24. use crmeb\services\crud\ViewApi;
  25. use crmeb\services\crud\ViewPages;
  26. use crmeb\services\crud\ViewRouter;
  27. use crmeb\services\FileService;
  28. use Phinx\Db\Adapter\AdapterFactory;
  29. use think\facade\Db;
  30. use think\helper\Str;
  31. use think\migration\db\Table;
  32. /**
  33. * Class SystemCrudServices
  34. * @author 等风来
  35. * @email 136327134@qq.com
  36. * @date 2023/4/6
  37. * @package app\services\system
  38. */
  39. class SystemCrudServices extends BaseServices
  40. {
  41. //不能生成的系统自带表
  42. const NOT_CRUD_TABANAME = [
  43. 'system_config', 'system_attachment', 'system_attachment_category', 'system_config_tab',
  44. 'system_admin', 'eb_system_city', 'system_log', 'system_menus', 'system_notice',
  45. 'system_notice_admin', 'system_notification', 'system_role', 'system_route',
  46. 'system_route_cate', 'system_storage', 'system_timer', 'system_user_level',
  47. 'system_crud', 'wechat_key', 'user_label_relation', 'user_brokerage_frozen',
  48. 'user_brokerage', 'store_product_cate', 'store_bargain_user_help', 'shipping_templates_region',
  49. 'shipping_templates_no_delivery', 'shipping_templates_free', 'other_order_status', 'lang_code',
  50. 'lang_country', 'app_version',
  51. ];
  52. /**
  53. * SystemCrudServices constructor.
  54. * @param SystemCrudDao $dao
  55. */
  56. public function __construct(SystemCrudDao $dao)
  57. {
  58. $this->dao = $dao;
  59. }
  60. /**
  61. * @return array
  62. * @author 等风来
  63. * @email 136327134@qq.com
  64. * @date 2023/4/11
  65. */
  66. public function getList()
  67. {
  68. [$page, $limit] = $this->getPageValue();
  69. $list = $this->dao->selectList([], 'add_time,id,name,table_name,table_comment,table_comment', $page, $limit, 'id desc');
  70. $count = $this->dao->count();
  71. return compact('list', 'count');
  72. }
  73. /**
  74. * 数据库字段类型
  75. * @return \string[][]
  76. * @author 等风来
  77. * @email 136327134@qq.com
  78. * @date 2023/4/11
  79. */
  80. public function getTabelRule()
  81. {
  82. $rule = [
  83. 'varchar' => 'string',
  84. 'int' => 'integer',
  85. 'biginteger' => 'bigint',
  86. 'tinyint' => 'boolean',
  87. ];
  88. return [
  89. 'types' => [
  90. 'varchar',
  91. 'char',
  92. 'text',
  93. 'longtext',
  94. 'tinytext',
  95. 'enum',
  96. 'blob',
  97. 'binary',
  98. 'varbinary',
  99. 'datetime',
  100. 'timestamp',
  101. 'time',
  102. 'date',
  103. 'year',
  104. 'boolean',
  105. 'tinyint',
  106. 'int',
  107. 'decimal',
  108. 'float',
  109. 'json',
  110. 'addTimestamps',
  111. 'addSoftDelete',
  112. ],
  113. 'rule' => $rule
  114. ];
  115. }
  116. /**
  117. * 改变数据库类型
  118. * @param string $type
  119. * @return string
  120. * @author 等风来
  121. * @email 136327134@qq.com
  122. * @date 2023/4/13
  123. */
  124. public function changeTabelRule(string $type)
  125. {
  126. if (!in_array($type, $this->getTabelRule()['types'])) {
  127. throw new AdminException(500047);
  128. }
  129. return $this->getTabelRule()['rule'][$type] ?? $type;
  130. }
  131. /**
  132. * @param string $tableName
  133. * @return mixed
  134. * @author 等风来
  135. * @email 136327134@qq.com
  136. * @date 2023/4/14
  137. */
  138. public function getTableInfo(string $tableName)
  139. {
  140. $sql = 'SELECT * FROM `information_schema`.`TABLES` WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?';
  141. $tableInfo = Db::query($sql, [config('database.connections.mysql.database'), $this->getTableName($tableName)]);
  142. return $tableInfo[0] ?? [];
  143. }
  144. /**
  145. * 获取表字段
  146. * @param string $tableName
  147. * @return mixed
  148. * @author 等风来
  149. * @email 136327134@qq.com
  150. * @date 2023/4/7
  151. */
  152. public function getColumnNamesList(string $tableName)
  153. {
  154. $sql = 'SELECT * FROM `information_schema`.`columns` WHERE TABLE_SCHEMA = ? AND table_name = ? ORDER BY ORDINAL_POSITION';
  155. $column = Db::query($sql, [config('database.connections.mysql.database'), $this->getTableName($tableName)]);
  156. $columns = [];
  157. foreach ($column as $item) {
  158. $column = [
  159. 'name' => $item['COLUMN_NAME'],
  160. 'type' => $item['DATA_TYPE'],
  161. 'dataType' => stripos($item['COLUMN_TYPE'], '(') !== false ? substr_replace($item['COLUMN_TYPE'], '', stripos($item['COLUMN_TYPE'], ')') + 1) : $item['COLUMN_TYPE'],
  162. 'default' => $item['COLUMN_DEFAULT'],
  163. 'null' => $item['IS_NULLABLE'] == 'YES',
  164. 'primaryKey' => $item['COLUMN_KEY'] == 'PRI',
  165. 'unsigned' => (bool)stripos($item['COLUMN_TYPE'], 'unsigned'),
  166. 'autoIncrement' => stripos($item['EXTRA'], 'auto_increment') !== false,
  167. 'comment' => $item['COLUMN_COMMENT'],
  168. 'limit' => $item['CHARACTER_MAXIMUM_LENGTH'] ?: $item['NUMERIC_PRECISION'],
  169. ];
  170. $columns[$item['COLUMN_NAME']] = $column;
  171. }
  172. return $columns;
  173. }
  174. /**
  175. * @param array $data
  176. * @return array
  177. * @author 等风来
  178. * @email 136327134@qq.com
  179. * @date 2023/4/12
  180. */
  181. public function valueReplace(array $data)
  182. {
  183. $replace = ['phar://'];
  184. $newData = [];
  185. foreach ($data as $key => $item) {
  186. if (is_array($item)) {
  187. $item = $this->valueReplace($item);
  188. } else {
  189. $item = str_replace($replace, '', $item);
  190. }
  191. $newData[str_replace($replace, '', $key)] = $item;
  192. }
  193. return $newData;
  194. }
  195. /**
  196. * 创建
  197. * @param array $data
  198. * @return mixed
  199. * @author 等风来
  200. * @email 136327134@qq.com
  201. * @date 2023/4/11
  202. */
  203. public function createCrud(array $data)
  204. {
  205. $tableName = $data['tableName'];
  206. $tableComment = $data['tableComment'] ?? $data['menuName'];
  207. $tableField = $this->valueReplace($data['tableField']);
  208. $filePath = $this->valueReplace($data['filePath']);
  209. if ($this->dao->value(['table_name' => $tableName])) {
  210. throw new AdminException(500048);
  211. }
  212. $data['softDelete'] = false;
  213. //创建数据库
  214. if ($tableField && !$data['isTable']) {
  215. $tableCreateInfo = $this->makeDatebase($tableName, $tableComment, $tableField);
  216. if ($tableCreateInfo['softDelete']) {
  217. $data['softDelete'] = true;
  218. }
  219. }
  220. if (in_array($tableName, self::NOT_CRUD_TABANAME)) {
  221. throw new AdminException(500044);
  222. }
  223. //读取表结构
  224. $column = $this->getColumnNamesList($tableName);
  225. if (!$column) {
  226. throw new AdminException(500049, ['_name' => $tableName]);
  227. }
  228. $tableInfo = $this->getTableInfo($tableName);
  229. //获取主键
  230. foreach ($column as $value) {
  231. if ($value['primaryKey']) {
  232. $data['key'] = $value['name'];
  233. break;
  234. }
  235. }
  236. $routeName = 'crud/' . Str::snake($tableName);
  237. $uniqueAuth = Str::snake($tableName) . '-crud-list-index';
  238. //增加保存的绝对路径
  239. foreach ($filePath as $k => $i) {
  240. if (in_array($k, ['pages', 'router', 'api'])) {
  241. $filePath[$k] = Make::adminTemplatePath() . $i;
  242. } else {
  243. $filePath[$k] = app()->getRootPath() . $i;
  244. }
  245. }
  246. //创建菜单
  247. if (!$data['menuName']) {
  248. $data['menuName'] = $tableName;
  249. }
  250. $dataMenu = [
  251. 'pid' => $data['pid'],
  252. 'menu_name' => $data['menuName'],
  253. 'menu_path' => '/' . $routeName . '/list',
  254. 'auth_type' => 1,
  255. 'is_show' => 1,
  256. 'is_del' => 0,
  257. 'unique_auth' => $uniqueAuth,
  258. 'is_header' => $data['pid'] ? 0 : 1,
  259. ];
  260. $res = $this->transaction(function () use ($tableInfo, $filePath, $tableName, $routeName, $data, $dataMenu) {
  261. $menuInfo = app()->make(SystemMenusServices::class)->save($dataMenu);
  262. //写入路由权限
  263. $cateId = app()->make(SystemRouteServices::class)->topCateId('adminapi');
  264. $ruleData = [
  265. [
  266. 'path' => $routeName,
  267. 'method' => 'GET',
  268. 'name' => $data['menuName'] . '列表接口',
  269. 'app_name' => 'adminapi',
  270. 'cate_id' => $cateId,
  271. 'unique_auth' => '',
  272. 'add_time' => date('Y-m-d H:i:s')
  273. ],
  274. [
  275. 'path' => $routeName . '/create',
  276. 'method' => 'GET',
  277. 'name' => $data['menuName'] . '获取创建表单接口',
  278. 'app_name' => 'adminapi',
  279. 'cate_id' => $cateId,
  280. 'unique_auth' => Str::snake($tableName) . '-add',
  281. 'add_time' => date('Y-m-d H:i:s')
  282. ],
  283. [
  284. 'path' => $routeName,
  285. 'method' => 'POST',
  286. 'name' => $data['menuName'] . '保存数据接口',
  287. 'app_name' => 'adminapi',
  288. 'cate_id' => $cateId,
  289. 'unique_auth' => '',
  290. 'add_time' => date('Y-m-d H:i:s')
  291. ],
  292. [
  293. 'path' => $routeName . '/<id>/edit',
  294. 'method' => 'GET',
  295. 'name' => $data['menuName'] . '获取修改表单接口',
  296. 'app_name' => 'adminapi',
  297. 'cate_id' => $cateId,
  298. 'unique_auth' => '',
  299. 'add_time' => date('Y-m-d H:i:s')
  300. ],
  301. [
  302. 'path' => $routeName . '/<id>',
  303. 'method' => 'PUT',
  304. 'name' => $data['menuName'] . '修改数据接口',
  305. 'app_name' => 'adminapi',
  306. 'cate_id' => $cateId,
  307. 'unique_auth' => '',
  308. 'add_time' => date('Y-m-d H:i:s')
  309. ],
  310. [
  311. 'path' => $routeName . '/<id>',
  312. 'method' => 'DELETE',
  313. 'name' => $data['menuName'] . '删除数据接口',
  314. 'app_name' => 'adminapi',
  315. 'cate_id' => $cateId,
  316. 'unique_auth' => '',
  317. 'add_time' => date('Y-m-d H:i:s')
  318. ],
  319. ];
  320. app()->make(SystemRouteServices::class)->saveAll($ruleData);
  321. //记录权限加入菜单表
  322. $menuData = [];
  323. foreach ($ruleData as $item) {
  324. $menuData[] = [
  325. 'pid' => $menuInfo->id,
  326. 'methods' => $item['method'],
  327. 'api_url' => $item['path'],
  328. 'unique_auth' => $item['unique_auth'],
  329. 'name' => $item['name'],
  330. 'is_del' => 0,
  331. ];
  332. }
  333. $menus = app()->make(SystemMenusServices::class)->saveAll($menuData);
  334. $menuIds = array_column($menus->toArray(), 'id');
  335. array_push($menuIds, $menuInfo->id);
  336. //生成文件
  337. $make = $this->makeFile($tableName, $routeName, config('app.crud_make', false), $data, $filePath);
  338. $makePath = [];
  339. foreach ($make as $key => $item) {
  340. $makePath[$key] = $item['path'];
  341. }
  342. //记录crud生成
  343. $res = $this->dao->save([
  344. 'pid' => $data['pid'],
  345. 'name' => $data['menuName'],
  346. 'table_name' => $tableName,
  347. 'table_comment' => $tableInfo['TABLE_COMMENT'] ?? '',
  348. 'table_collation' => $tableInfo['TABLE_COLLATION'] ?? '',
  349. 'field' => json_encode($data),//提交的数据
  350. 'menu_ids' => json_encode($menuIds),//生成的菜单id
  351. 'make_path' => json_encode($makePath),
  352. 'add_time' => time()
  353. ]);
  354. return $res;
  355. });
  356. return $res->toArray();
  357. }
  358. /**
  359. * 获取数据库配置
  360. * @return array
  361. */
  362. protected function getDbConfig(): array
  363. {
  364. $default = app()->config->get('database.default');
  365. $config = app()->config->get("database.connections.{$default}");
  366. if (0 == $config['deploy']) {
  367. $dbConfig = [
  368. 'adapter' => $config['type'],
  369. 'host' => $config['hostname'],
  370. 'name' => $config['database'],
  371. 'user' => $config['username'],
  372. 'pass' => $config['password'],
  373. 'port' => $config['hostport'],
  374. 'charset' => $config['charset'],
  375. 'table_prefix' => $config['prefix'],
  376. ];
  377. } else {
  378. $dbConfig = [
  379. 'adapter' => explode(',', $config['type'])[0],
  380. 'host' => explode(',', $config['hostname'])[0],
  381. 'name' => explode(',', $config['database'])[0],
  382. 'user' => explode(',', $config['username'])[0],
  383. 'pass' => explode(',', $config['password'])[0],
  384. 'port' => explode(',', $config['hostport'])[0],
  385. 'charset' => explode(',', $config['charset'])[0],
  386. 'table_prefix' => explode(',', $config['prefix'])[0],
  387. ];
  388. }
  389. $table = app()->config->get('database.migration_table', 'migrations');
  390. $dbConfig['default_migration_table'] = $dbConfig['table_prefix'] . $table;
  391. return $dbConfig;
  392. }
  393. public function getAdapter()
  394. {
  395. $options = $this->getDbConfig();
  396. $adapter = AdapterFactory::instance()->getAdapter($options['adapter'], $options);
  397. if ($adapter->hasOption('table_prefix') || $adapter->hasOption('table_suffix')) {
  398. $adapter = AdapterFactory::instance()->getWrapper('prefix', $adapter);
  399. }
  400. return $adapter;
  401. }
  402. /**
  403. * 创建数据库
  404. * @param string $tableName
  405. * @param string $tableComment
  406. * @param array $tableField
  407. * @return array
  408. * @author 等风来
  409. * @email 136327134@qq.com
  410. * @date 2023/4/7
  411. */
  412. public function makeDatebase(string $tableName, string $tableComment, array $tableField = [])
  413. {
  414. $softDelete = false;
  415. $timestamps = false;
  416. $indexField = [];
  417. //创建表
  418. $table = new Table($tableName, ['comment' => $tableComment], $this->getAdapter());
  419. //创建字段
  420. foreach ($tableField as $item) {
  421. $option = [];
  422. if (isset($item['limit'])) {
  423. $option['limit'] = (int)$item['limit'];
  424. }
  425. if (isset($item['default'])) {
  426. $option['default'] = $item['default'];
  427. }
  428. //创建伪删除
  429. if ($item['field_type'] === 'addSoftDelete') {
  430. $table->addSoftDelete();
  431. $softDelete = true;
  432. } else if ($item['field_type'] === 'addTimestamps') {
  433. //创建修改和增加时间
  434. $table->addTimestamps();
  435. $timestamps = true;
  436. } else {
  437. $option['comment'] = $item['comment'];
  438. $table->addColumn($item['field'], $this->changeTabelRule($item['field_type']), $option);
  439. }
  440. }
  441. //创建索引
  442. if (!empty($data['tableIndex'])) {
  443. $indexField = $data['tableIndex'];
  444. foreach ($data['tableIndex'] as $item) {
  445. $table->addIndex($item);
  446. }
  447. }
  448. //执行创建
  449. $table->create();
  450. return compact('indexField', 'softDelete', 'timestamps');
  451. }
  452. /**
  453. * 创建文件返回文件路径和内容
  454. * @param string $tableName
  455. * @param string $routeName
  456. * @param bool $isMake
  457. * @param array $options
  458. * @param array $filePath
  459. * @param string $basePath
  460. * @return array[]
  461. * @author 等风来
  462. * @email 136327134@qq.com
  463. * @date 2023/4/7
  464. */
  465. public function makeFile(string $tableName, string $routeName, bool $isMake = false, array $options = [], array $filePath = [], string $basePath = '')
  466. {
  467. $options['fromField'] = is_array($options['fromField']) ? $options['fromField'] : [];
  468. $options['columnField'] = is_array($options['columnField']) ? $options['columnField'] : [];
  469. //生成模型
  470. $model = app()->make(Model::class);
  471. $model->setFilePathName($filePath['model'] ?? '')->setbasePath($basePath)->handle($tableName, $options);
  472. //生成dao
  473. $dao = app()->make(Dao::class);
  474. $dao->setFilePathName($filePath['dao'] ?? '')->setbasePath($basePath)->handle($tableName, [
  475. 'usePath' => $model->getUsePath(),
  476. ]);
  477. //生成service
  478. $service = app()->make(Service::class);
  479. $service->setFilePathName($filePath['service'] ?? '')->setbasePath($basePath)->handle($tableName, [
  480. 'field' => $options['fromField'],
  481. 'usePath' => $dao->getUsePath(),
  482. ]);
  483. //生成验证器
  484. $validate = app()->make(Validate::class);
  485. $validate->setFilePathName($filePath['validate'] ?? '')->setbasePath($basePath)->handle($tableName);
  486. //生成控制器
  487. $controller = app()->make(Controller::class);
  488. $controller->setFilePathName($filePath['controller'] ?? '')->setbasePath($basePath)->handle($tableName, [
  489. 'usePath' => $service->getUsePath(),
  490. 'validateName' => '\\' . str_replace('/', '\\', $validate->getUsePath()) . '::class',
  491. 'field' => array_column($options['fromField'], 'field'),
  492. ]);
  493. //生成路由
  494. $route = app()->make(Route::class);
  495. $route->setFilePathName($filePath['route'] ?? '')->setbasePath($basePath)->handle($tableName, [
  496. 'menus' => $options['menuName'],
  497. 'route' => $routeName
  498. ]);
  499. //生成前台路由
  500. $viewRouter = app()->make(ViewRouter::class);
  501. $viewRouter->setFilePathName($filePath['router'] ?? '')->setbasePath($basePath)->handle($tableName, [
  502. 'route' => $routeName,
  503. 'menuName' => $options['menuName'],
  504. ]);
  505. //生成前台接口
  506. $viewApi = app()->make(ViewApi::class);
  507. $viewApi->setFilePathName($filePath['api'] ?? '')->setbasePath($basePath)->handle($tableName, [
  508. 'route' => $routeName,
  509. ]);
  510. //生成前台页面
  511. $viewPages = app()->make(ViewPages::class);
  512. $viewPages->setFilePathName($filePath['pages'] ?? '')->setbasePath($basePath)->handle($tableName, [
  513. 'field' => $options['columnField'],
  514. 'route' => $routeName,
  515. 'pathApiJs' => '@/' . str_replace('\\', '/', str_replace([Make::adminTemplatePath(), '.js'], '', $viewApi->getPath())),
  516. ]);
  517. //创建文件
  518. if ($isMake) {
  519. FileService::batchMakeFiles([$model, $dao, $service, $controller, $route, $viewApi, $viewPages, $viewRouter]);
  520. }
  521. return [
  522. 'controller' => [
  523. 'path' => $this->replace($controller->getPath()),
  524. 'content' => $controller->getContent()
  525. ],
  526. 'model' => [
  527. 'path' => $this->replace($model->getPath()),
  528. 'content' => $model->getContent()
  529. ],
  530. 'dao' => [
  531. 'path' => $this->replace($dao->getPath()),
  532. 'content' => $dao->getContent()
  533. ],
  534. 'route' => [
  535. 'path' => $this->replace($route->getPath()),
  536. 'content' => $route->getContent()
  537. ],
  538. 'service' => [
  539. 'path' => $this->replace($service->getPath()),
  540. 'content' => $service->getContent()
  541. ],
  542. 'validate' => [
  543. 'path' => $this->replace($validate->getPath()),
  544. 'content' => $validate->getContent()
  545. ],
  546. 'router' => [
  547. 'path' => $this->replace($viewRouter->getPath()),
  548. 'content' => $viewRouter->getContent()
  549. ],
  550. 'api' => [
  551. 'path' => $this->replace($viewApi->getPath()),
  552. 'content' => $viewApi->getContent()
  553. ],
  554. 'pages' => [
  555. 'path' => $this->replace($viewPages->getPath()),
  556. 'content' => $viewPages->getContent()
  557. ],
  558. ];
  559. }
  560. protected function replace(string $path)
  561. {
  562. return str_replace([app()->getRootPath(), Make::adminTemplatePath()], '', $path);
  563. }
  564. /**
  565. * @param string $tableName
  566. * @param bool $fullName
  567. * @return string
  568. * @author 等风来
  569. * @email 136327134@qq.com
  570. * @date 2023/4/7
  571. */
  572. public function getTableName(string $tableName, bool $fullName = true)
  573. {
  574. $tablePrefix = config('database.connections.mysql.prefix');
  575. $pattern = '/^' . $tablePrefix . '/i';
  576. return ($fullName ? $tablePrefix : '') . (preg_replace($pattern, '', $tableName));
  577. }
  578. }