SystemCrudServices.php 22 KB

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