SystemCrudServices.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  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', 'user', 'wechat_user', 'template_message', 'store_order', 'other_order',
  51. 'store_order_cart_info', 'store_order_economize', 'store_order_invoice', 'store_order_refund',
  52. 'store_order_status', 'store_pink', 'agent_level', 'agent_level_task', 'agent_level_task_record',
  53. 'agreement', 'app_version', 'article', 'article_category', 'article_content', 'auxiliary', 'cache',
  54. 'capital_flow', 'category', 'diy', 'express', 'lang_type', 'live_anchor', 'live_goods', 'live_room',
  55. 'live_room_goods', 'luck_lottery', 'luck_lottery_record', 'luck_prize', 'member_card', 'member_card_batch',
  56. 'member_right', 'member_ship', 'message_system', 'other_order', 'other_order_status', 'out_account', 'out_interface',
  57. 'page_categroy', 'page_link', 'qrcode', 'shipping_templates', 'shipping_templates_free', 'shipping_templates_no_delivery',
  58. 'shipping_templates_region', 'sms_record', 'store_advance', 'store_bargain', 'store_bargain_user', 'store_bargain_user_help',
  59. 'store_cart', 'store_category', 'store_combination', 'store_coupon_issue', 'store_coupon_issue_user', 'store_coupon_product',
  60. 'store_coupon_user', 'store_integral', 'store_integral_order', 'store_integral_order_status', 'store_order', 'store_order_cart_info',
  61. 'store_order_economize', 'store_order_invoice', 'store_order_refund', 'store_order_status', 'store_pink', 'store_product',
  62. 'store_product_attr', 'store_product_attr_result', 'store_product_attr_value', 'store_product_cate', 'store_product_coupon',
  63. 'store_product_description', 'store_product_log', 'store_product_relation', 'store_service', 'store_service_feedback',
  64. 'store_product_reply', 'store_product_rule', 'store_product_virtual', 'store_seckill', 'store_seckill_time',
  65. 'store_service_log', 'store_service_record', 'store_service_speechcraft', 'store_visit', 'system_attachment',
  66. 'system_attachment_category', 'system_city', 'system_config', 'system_config_tab', 'system_file', 'system_file_info',
  67. 'system_group', 'system_group_data', 'system_log', 'system_notice', 'system_notice_admin', 'system_notification',
  68. 'system_role', 'system_route', 'system_route_cate', 'system_storage', 'system_store', 'system_store_staff',
  69. 'system_timer', 'system_user_level', 'template_message', 'upgrade_log', 'user', 'user_address',
  70. 'user_bill', 'user_brokerage', 'user_brokerage_frozen', 'user_cancel', 'user_enter', 'user_extract',
  71. 'user_friends', 'user_group', 'user_invoice', 'user_label', 'user_label_relation', 'user_level', 'user_money',
  72. 'user_notice', 'user_notice_see', 'user_recharge', 'user_search', 'user_sign', 'user_spread',
  73. 'user_visit', 'wechat_key', 'wechat_media', 'wechat_message', 'wechat_news_category', 'wechat_qrcode',
  74. 'wechat_qrcode_cate', 'wechat_qrcode_record', 'wechat_reply', 'wechat_user'
  75. ];
  76. /**
  77. * SystemCrudServices constructor.
  78. * @param SystemCrudDao $dao
  79. */
  80. public function __construct(SystemCrudDao $dao)
  81. {
  82. $this->dao = $dao;
  83. }
  84. /**
  85. * @return array
  86. * @author 等风来
  87. * @email 136327134@qq.com
  88. * @date 2023/4/11
  89. */
  90. public function getList()
  91. {
  92. [$page, $limit] = $this->getPageValue();
  93. $list = $this->dao->selectList([], 'add_time,id,name,table_name,table_comment,table_collation', $page, $limit, 'id desc');
  94. $count = $this->dao->count();
  95. return compact('list', 'count');
  96. }
  97. /**
  98. * 数据库字段类型
  99. * @return \string[][]
  100. * @author 等风来
  101. * @email 136327134@qq.com
  102. * @date 2023/4/11
  103. */
  104. public function getTabelRule()
  105. {
  106. $rule = [
  107. 'varchar' => 'string',
  108. 'int' => 'integer',
  109. 'biginteger' => 'bigint',
  110. 'tinyint' => 'boolean',
  111. ];
  112. return [
  113. 'types' => [
  114. 'varchar',
  115. 'char',
  116. 'text',
  117. 'longtext',
  118. 'tinytext',
  119. // 'enum',
  120. 'blob',
  121. 'binary',
  122. 'varbinary',
  123. 'datetime',
  124. 'timestamp',
  125. 'time',
  126. 'date',
  127. 'year',
  128. 'boolean',
  129. 'tinyint',
  130. 'int',
  131. 'decimal',
  132. 'float',
  133. 'json',
  134. 'addTimestamps',
  135. 'addSoftDelete',
  136. ],
  137. 'form' => [
  138. [
  139. 'value' => 'input',
  140. 'label' => '输入框',
  141. ],
  142. [
  143. 'value' => 'number',
  144. 'label' => '数字输入框',
  145. ],
  146. [
  147. 'value' => 'textarea',
  148. 'label' => '多行文本框',
  149. ],
  150. [
  151. 'value' => 'dateTime',
  152. 'label' => '单选日期时间',
  153. ],
  154. // [
  155. // 'value' => 'dateTimeRange',
  156. // 'label' => '日期时间区间选择',
  157. // ],
  158. [
  159. 'value' => 'checkbox',
  160. 'label' => '多选框',
  161. ],
  162. [
  163. 'value' => 'radio',
  164. 'label' => '单选框',
  165. ],
  166. [
  167. 'value' => 'select',
  168. 'label' => '下拉框',
  169. ],
  170. [
  171. 'value' => 'frameImageOne',
  172. 'label' => '单图选择'
  173. ],
  174. [
  175. 'value' => 'frameImages',
  176. 'label' => '多图选择'
  177. ],
  178. ],
  179. 'rule' => $rule
  180. ];
  181. }
  182. /**
  183. * 改变数据库类型
  184. * @param string $type
  185. * @return string
  186. * @author 等风来
  187. * @email 136327134@qq.com
  188. * @date 2023/4/13
  189. */
  190. public function changeTabelRule(string $type)
  191. {
  192. if (!in_array($type, $this->getTabelRule()['types'])) {
  193. throw new AdminException(500047);
  194. }
  195. return $this->getTabelRule()['rule'][$type] ?? $type;
  196. }
  197. /**
  198. * @param string $tableName
  199. * @return mixed
  200. * @author 等风来
  201. * @email 136327134@qq.com
  202. * @date 2023/4/14
  203. */
  204. public function getTableInfo(string $tableName)
  205. {
  206. $sql = 'SELECT * FROM `information_schema`.`TABLES` WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?';
  207. $tableInfo = Db::query($sql, [config('database.connections.mysql.database'), $this->getTableName($tableName)]);
  208. return $tableInfo[0] ?? [];
  209. }
  210. /**
  211. * 获取表字段
  212. * @param string $tableName
  213. * @return mixed
  214. * @author 等风来
  215. * @email 136327134@qq.com
  216. * @date 2023/4/7
  217. */
  218. public function getColumnNamesList(string $tableName)
  219. {
  220. $sql = 'SELECT * FROM `information_schema`.`columns` WHERE TABLE_SCHEMA = ? AND table_name = ? ORDER BY ORDINAL_POSITION';
  221. $column = Db::query($sql, [config('database.connections.mysql.database'), $this->getTableName($tableName)]);
  222. $columns = [];
  223. foreach ($column as $item) {
  224. $column = [
  225. 'name' => $item['COLUMN_NAME'],
  226. 'type' => $item['DATA_TYPE'],
  227. 'dataType' => stripos($item['COLUMN_TYPE'], '(') !== false ? substr_replace($item['COLUMN_TYPE'], '', stripos($item['COLUMN_TYPE'], ')') + 1) : $item['COLUMN_TYPE'],
  228. 'default' => $item['COLUMN_DEFAULT'],
  229. 'null' => $item['IS_NULLABLE'] == 'YES',
  230. 'primaryKey' => $item['COLUMN_KEY'] == 'PRI',
  231. 'unsigned' => (bool)stripos($item['COLUMN_TYPE'], 'unsigned'),
  232. 'autoIncrement' => stripos($item['EXTRA'], 'auto_increment') !== false,
  233. 'comment' => $item['COLUMN_COMMENT'],
  234. 'limit' => $item['CHARACTER_MAXIMUM_LENGTH'] ?: $item['NUMERIC_PRECISION'],
  235. ];
  236. $columns[$item['COLUMN_NAME']] = $column;
  237. }
  238. return $columns;
  239. }
  240. /**
  241. * @param array $data
  242. * @return array
  243. * @author 等风来
  244. * @email 136327134@qq.com
  245. * @date 2023/4/12
  246. */
  247. public function valueReplace(array $data)
  248. {
  249. $replace = ['phar://'];
  250. $newData = [];
  251. foreach ($data as $key => $item) {
  252. if (is_array($item)) {
  253. $item = $this->valueReplace($item);
  254. } else {
  255. $item = str_replace($replace, '', $item);
  256. }
  257. $newData[str_replace($replace, '', $key)] = $item;
  258. }
  259. return $newData;
  260. }
  261. /**
  262. * 更新表字段
  263. * @param string $tableName
  264. * @param string $field
  265. * @param string $changeFiled
  266. * @param string $type
  267. * @param string $limit
  268. * @param string $default
  269. * @param string $comment
  270. * @param array $options
  271. * @return mixed
  272. * @author 等风来
  273. * @email 136327134@qq.com
  274. * @date 2023/4/24
  275. */
  276. protected function updateAlter(string $tableName, string $field, string $changeFiled, string $type, $limit = '', string $default = '', string $comment = '', array $options = [])
  277. {
  278. $tableName = $this->getTableName($tableName);
  279. $comment = addslashes($comment);
  280. $field = addslashes($field);
  281. $changeFiled = addslashes($changeFiled);
  282. $type = addslashes($type);
  283. $default = addslashes($default);
  284. if (in_array(strtolower($type), ['text', 'longtext', 'tinytext'])) {
  285. $sql = "ALTER TABLE `$tableName` CHANGE `$field` `$changeFiled` $type CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '$comment';";
  286. } else {
  287. $sql = "ALTER TABLE `$tableName` CHANGE `$field` `$changeFiled` $type($limit) NOT NULL DEFAULT '$default' COMMENT '$comment';";
  288. }
  289. return Db::execute($sql);
  290. }
  291. /**
  292. * 添加字段
  293. * @param string $tableName
  294. * @param string $field
  295. * @param string $prevFiled
  296. * @param string $type
  297. * @param string $limit
  298. * @param string $default
  299. * @param string $comment
  300. * @param array $options
  301. * @return mixed
  302. * @author 等风来
  303. * @email 136327134@qq.com
  304. * @date 2023/4/24
  305. */
  306. public function addAlter(string $tableName, string $field, string $prevFiled, string $type, $limit = '', string $default = '', string $comment = '', array $options = [])
  307. {
  308. $tableName = $this->getTableName($tableName);
  309. $comment = addslashes($comment);
  310. $field = addslashes($field);
  311. $prevFiled = addslashes($prevFiled);
  312. $type = addslashes($type);
  313. $default = addslashes($default);
  314. if ($prevFiled) {
  315. $after = "AFTER `$prevFiled`";
  316. } else {
  317. $after = "";
  318. }
  319. if (in_array(strtolower($type), ['text', 'longtext', 'tinytext'])) {
  320. $sql = "ALTER TABLE `$tableName` ADD `$field` $type NULL COMMENT '$comment' $after;";
  321. } else {
  322. $sql = "ALTER TABLE `$tableName` ADD `$field` $type($limit) NOT NULL DEFAULT '$default' COMMENT '$comment' $after;";
  323. }
  324. return Db::execute($sql);
  325. }
  326. /**
  327. * 删除表字段
  328. * @param string $tableName
  329. * @param string $field
  330. * @return mixed
  331. * @author 等风来
  332. * @email 136327134@qq.com
  333. * @date 2023/4/24
  334. */
  335. protected function deleteAlter(string $tableName, string $field)
  336. {
  337. $tableName = $this->getTableName($tableName);
  338. $field = addslashes($field);
  339. $sql = "ALTER TABLE `$tableName` DROP `$field`";
  340. return Db::execute($sql);
  341. }
  342. /**
  343. * 修改表备注
  344. * @param string $tableName
  345. * @param string $common
  346. * @return mixed
  347. * @author 等风来
  348. * @email 136327134@qq.com
  349. * @date 2023/4/24
  350. */
  351. protected function updateFromCommon(string $tableName, string $common)
  352. {
  353. $tableName = $this->getTableName($tableName);
  354. $common = addslashes($common);
  355. $sql = "ALTER TABLE `$tableName` COMMENT = '$common';";
  356. return Db::execute($sql);
  357. }
  358. /**
  359. * 对比字段变动了更改
  360. * @param string $tableName
  361. * @param array $deleteField
  362. * @param array $tableField
  363. * @author 等风来
  364. * @email 136327134@qq.com
  365. * @date 2023/4/24
  366. */
  367. protected function diffAlter(string $tableName, array $deleteField, array $tableField)
  368. {
  369. $updateAlter = [];
  370. $addAlter = [];
  371. $columns = $this->getColumnNamesList($tableName);
  372. $fieldAll = array_column($columns, 'name');
  373. $prevFiled = $columns[count($columns) - 1]['name'] ?? '';
  374. //对比数据库字段
  375. foreach ($tableField as $item) {
  376. if ($item['primaryKey']) {
  377. continue;
  378. }
  379. //前台新增的字段进行添加
  380. if (!(isset($item['default_field']) &&
  381. isset($item['default_field_type']) &&
  382. isset($item['default_limit']) &&
  383. isset($item['default_comment']) &&
  384. isset($item['default_default']))
  385. ) {
  386. if (!in_array($item['field'], $fieldAll)) {
  387. $addAlter[] = [
  388. 'prev_filed' => $prevFiled,
  389. 'field' => $item['field'],
  390. 'limit' => $item['limit'],
  391. 'type' => $item['field_type'],
  392. 'comment' => $item['comment'],
  393. 'default' => $item['default'],
  394. ];
  395. }
  396. continue;
  397. } else {
  398. //默认字段没有在数据库中,需要添加字段
  399. if (!in_array($item['default_field'], $fieldAll)) {
  400. $addAlter[] = [
  401. 'prev_filed' => $prevFiled,
  402. 'field' => $item['field'],
  403. 'limit' => $item['limit'],
  404. 'type' => $item['field_type'],
  405. 'comment' => $item['comment'],
  406. 'default' => $item['default'],
  407. ];
  408. continue;
  409. }
  410. }
  411. if ($item['default_field'] != $item['field'] && in_array($item['field_type'], ['addTimestamps', 'addSoftDelete'])) {
  412. throw new AdminException($item['field'] . '字段不允许被更改');
  413. }
  414. //数据库表存在的,字段,并且被修改
  415. if ($item['default_field'] != $item['field'] ||
  416. $item['default_field_type'] != $item['field_type'] ||
  417. $item['default_limit'] != $item['limit'] ||
  418. $item['default_comment'] != $item['comment'] ||
  419. $item['default_default'] != $item['default']) {
  420. $updateAlter[] = [
  421. 'default_field' => $item['default_field'],
  422. 'field' => $item['field'],
  423. 'limit' => $item['limit'],
  424. 'type' => $item['field_type'],
  425. 'comment' => $item['comment'],
  426. 'default' => $item['default'],
  427. ];
  428. }
  429. }
  430. //更新数据库字段
  431. foreach ($updateAlter as $item) {
  432. $this->updateAlter($tableName, $item['default_field'], $item['field'], $item['type'], $item['limit'], $item['default'], $item['comment']);
  433. }
  434. //添加字段
  435. foreach ($addAlter as $item) {
  436. $this->addAlter($tableName, $item['field'], $item['prev_filed'], $item['type'], $item['limit'], $item['default'], $item['comment']);
  437. }
  438. //删除多余字段
  439. foreach ($deleteField as $item) {
  440. $this->deleteAlter($tableName, $item);
  441. }
  442. }
  443. /**
  444. * 创建
  445. * @param array $data
  446. * @return mixed
  447. * @author 等风来
  448. * @email 136327134@qq.com
  449. * @date 2023/4/11
  450. */
  451. public function createCrud(int $id, array $data)
  452. {
  453. $tableName = $data['tableName'];
  454. $tableField = $this->valueReplace($data['tableField']);
  455. $filePath = $this->valueReplace($data['filePath']);
  456. $modelName = !empty($data['modelName']) ? $data['modelName'] : $tableName;
  457. $tableComment = !empty($data['tableComment']) ? $data['tableComment'] : $modelName;
  458. //检测是否为系统表
  459. if (in_array($tableName, self::NOT_CRUD_TABANAME)) {
  460. throw new AdminException(500044);
  461. }
  462. $data['softDelete'] = false;
  463. $tableInfo = null;
  464. if ($id) {
  465. $this->updateFromCommon($tableName, $tableComment);
  466. //删除数据库表
  467. $tableInfo = $this->getTableInfo($tableName);
  468. if ($tableInfo) {
  469. //对比字段进行更新/删除字段
  470. $this->diffAlter($tableName, $data['deleteField'], $tableField);
  471. }
  472. } else {
  473. if ($this->dao->count(['table_name' => $tableName])) {
  474. throw new AdminException('表已经被生成过,请在列表中进行修改');
  475. }
  476. }
  477. //创建数据库
  478. if ($tableField && (!$data['isTable'] || !$tableInfo)) {
  479. $tableCreateInfo = $this->makeDatebase($tableName, $tableComment, $tableField);
  480. if ($tableCreateInfo['softDelete']) {
  481. $data['softDelete'] = true;
  482. }
  483. }
  484. //读取表结构
  485. $column = $this->getColumnNamesList($tableName);
  486. if (!$column) {
  487. throw new AdminException(500049, ['_name' => $tableName]);
  488. }
  489. //读取数据库字段信息
  490. $tableInfo = $this->getTableInfo($tableName);
  491. //获取主键
  492. foreach ($column as $value) {
  493. if ($value['primaryKey']) {
  494. $data['key'] = $value['name'];
  495. break;
  496. }
  497. }
  498. $routeName = 'crud/' . Str::snake($tableName);
  499. $uniqueAuth = Str::snake($tableName) . '-crud-list-index';
  500. //增加保存的绝对路径
  501. foreach ($filePath as $k => $i) {
  502. if (in_array($k, ['pages', 'router', 'api'])) {
  503. $filePath[$k] = Make::adminTemplatePath() . $i;
  504. } else {
  505. $filePath[$k] = app()->getRootPath() . $i;
  506. }
  507. }
  508. //创建菜单
  509. if (!$data['menuName']) {
  510. $data['menuName'] = $tableName;
  511. }
  512. $dataMenu = [
  513. 'pid' => $data['pid'],
  514. 'menu_name' => $data['menuName'],
  515. 'menu_path' => '/' . $routeName,
  516. 'auth_type' => 1,
  517. 'is_show' => 1,
  518. 'is_del' => 0,
  519. 'unique_auth' => $uniqueAuth,
  520. 'is_header' => $data['pid'] ? 0 : 1,
  521. ];
  522. $crudInfo = null;
  523. if ($id) {
  524. $crudInfo = $this->dao->get($id);
  525. }
  526. $res = $this->transaction(function () use ($crudInfo, $tableInfo, $modelName, $filePath, $tableName, $routeName, $data, $dataMenu) {
  527. $routeService = app()->make(SystemRouteServices::class);
  528. $meunService = app()->make(SystemMenusServices::class);
  529. //修改菜单名称
  530. if ($crudInfo) {
  531. //菜单存在的时候进行修改
  532. if ($crudInfo->menu_id && $meunService->value(['id' => [$crudInfo->menu_id]], 'id')) {
  533. $meunService->update($crudInfo->menu_id, $dataMenu);
  534. $menuInfo = (object)['id' => $crudInfo->menu_id];
  535. } else {
  536. $menuInfo = $meunService->save($dataMenu);
  537. }
  538. //删除掉添加的路由权限
  539. if ($crudInfo->route_ids) {
  540. $routeService->deleteRoutes($crudInfo->route_ids);
  541. }
  542. //删除掉权限路由
  543. if ($crudInfo->menu_ids) {
  544. app()->make(SystemMenusServices::class)->deleteMenus($crudInfo->menu_ids);
  545. }
  546. } else {
  547. $menuInfo = $meunService->save($dataMenu);
  548. }
  549. //写入路由权限
  550. $cateId = app()->make(SystemRouteServices::class)->topCateId('adminapi', 'CRUD');
  551. $ruleData = [
  552. [
  553. 'path' => $routeName,
  554. 'method' => 'GET',
  555. 'name' => $modelName . '列表接口',
  556. 'app_name' => 'adminapi',
  557. 'cate_id' => $cateId,
  558. 'unique_auth' => '',
  559. 'add_time' => date('Y-m-d H:i:s')
  560. ],
  561. [
  562. 'path' => $routeName . '/create',
  563. 'method' => 'GET',
  564. 'name' => $modelName . '获取创建表单接口',
  565. 'app_name' => 'adminapi',
  566. 'cate_id' => $cateId,
  567. 'unique_auth' => Str::snake($tableName) . '-add',
  568. 'add_time' => date('Y-m-d H:i:s')
  569. ],
  570. [
  571. 'path' => $routeName,
  572. 'method' => 'POST',
  573. 'name' => $modelName . '保存接口',
  574. 'app_name' => 'adminapi',
  575. 'cate_id' => $cateId,
  576. 'unique_auth' => '',
  577. 'add_time' => date('Y-m-d H:i:s')
  578. ],
  579. [
  580. 'path' => $routeName . '/<id>/edit',
  581. 'method' => 'GET',
  582. 'name' => $modelName . '获取修改表单接口',
  583. 'app_name' => 'adminapi',
  584. 'cate_id' => $cateId,
  585. 'unique_auth' => '',
  586. 'add_time' => date('Y-m-d H:i:s')
  587. ],
  588. [
  589. 'path' => $routeName . '/<id>',
  590. 'method' => 'PUT',
  591. 'name' => $modelName . '修改接口',
  592. 'app_name' => 'adminapi',
  593. 'cate_id' => $cateId,
  594. 'unique_auth' => '',
  595. 'add_time' => date('Y-m-d H:i:s')
  596. ],
  597. [
  598. 'path' => $routeName . '/<id>',
  599. 'method' => 'DELETE',
  600. 'name' => $modelName . '删除接口',
  601. 'app_name' => 'adminapi',
  602. 'cate_id' => $cateId,
  603. 'unique_auth' => '',
  604. 'add_time' => date('Y-m-d H:i:s')
  605. ],
  606. ];
  607. $routeList = $routeService->saveAll($ruleData);
  608. $routeIds = array_column($routeList->toArray(), 'id');
  609. //记录权限加入菜单表
  610. $menuData = [];
  611. foreach ($ruleData as $item) {
  612. $menuData[] = [
  613. 'pid' => $menuInfo->id ?: 0,
  614. 'methods' => $item['method'],
  615. 'api_url' => $item['path'],
  616. 'unique_auth' => $item['unique_auth'],
  617. 'menu_name' => $item['name'],
  618. 'is_del' => 0,
  619. 'auth_type' => 2,
  620. ];
  621. }
  622. $menus = app()->make(SystemMenusServices::class)->saveAll($menuData);
  623. $menuIds = array_column($menus->toArray(), 'id');
  624. //生成文件
  625. $make = $this->makeFile($tableName, $routeName, true, $data, $filePath);
  626. $makePath = [];
  627. foreach ($make as $key => $item) {
  628. $makePath[$key] = $item['path'];
  629. }
  630. $crudDate = [
  631. 'pid' => $data['pid'],
  632. 'name' => $data['menuName'],
  633. 'model_name' => $data['modelName'],
  634. 'table_name' => $tableName,
  635. 'table_comment' => $tableInfo['TABLE_COMMENT'] ?? '',
  636. 'table_collation' => $tableInfo['TABLE_COLLATION'] ?? '',
  637. 'field' => json_encode($data),//提交的数据
  638. 'menu_ids' => json_encode($menuIds),//生成的菜单id
  639. 'menu_id' => $menuInfo->id,//生成的菜单id
  640. 'make_path' => json_encode($makePath),
  641. 'route_ids' => json_encode($routeIds),
  642. ];
  643. if ($crudInfo) {
  644. $res = $this->dao->update($crudInfo->id, $crudDate);
  645. } else {
  646. $crudDate['add_time'] = time();
  647. //记录crud生成
  648. $res = $this->dao->save($crudDate);
  649. }
  650. return $res;
  651. });
  652. return $res->toArray();
  653. }
  654. /**
  655. * 获取数据库配置
  656. * @return array
  657. */
  658. protected function getDbConfig(): array
  659. {
  660. $default = app()->config->get('database.default');
  661. $config = app()->config->get("database.connections.{$default}");
  662. if (0 == $config['deploy']) {
  663. $dbConfig = [
  664. 'adapter' => $config['type'],
  665. 'host' => $config['hostname'],
  666. 'name' => $config['database'],
  667. 'user' => $config['username'],
  668. 'pass' => $config['password'],
  669. 'port' => $config['hostport'],
  670. 'charset' => $config['charset'],
  671. 'table_prefix' => $config['prefix'],
  672. ];
  673. } else {
  674. $dbConfig = [
  675. 'adapter' => explode(',', $config['type'])[0],
  676. 'host' => explode(',', $config['hostname'])[0],
  677. 'name' => explode(',', $config['database'])[0],
  678. 'user' => explode(',', $config['username'])[0],
  679. 'pass' => explode(',', $config['password'])[0],
  680. 'port' => explode(',', $config['hostport'])[0],
  681. 'charset' => explode(',', $config['charset'])[0],
  682. 'table_prefix' => explode(',', $config['prefix'])[0],
  683. ];
  684. }
  685. $table = app()->config->get('database.migration_table', 'migrations');
  686. $dbConfig['default_migration_table'] = $dbConfig['table_prefix'] . $table;
  687. return $dbConfig;
  688. }
  689. public function getAdapter()
  690. {
  691. $options = $this->getDbConfig();
  692. $adapter = AdapterFactory::instance()->getAdapter($options['adapter'], $options);
  693. if ($adapter->hasOption('table_prefix') || $adapter->hasOption('table_suffix')) {
  694. $adapter = AdapterFactory::instance()->getWrapper('prefix', $adapter);
  695. }
  696. return $adapter;
  697. }
  698. /**
  699. * 创建数据库
  700. * @param string $tableName
  701. * @param string $tableComment
  702. * @param array $tableField
  703. * @return array
  704. * @author 等风来
  705. * @email 136327134@qq.com
  706. * @date 2023/4/7
  707. */
  708. public function makeDatebase(string $tableName, string $tableComment, array $tableField = [])
  709. {
  710. $softDelete = false;
  711. $timestamps = false;
  712. $indexField = [];
  713. //创建表
  714. $table = new Table($tableName, ['comment' => $tableComment], $this->getAdapter());
  715. //创建字段
  716. foreach ($tableField as $item) {
  717. if (isset($item['primaryKey']) && $item['primaryKey']) {
  718. continue;
  719. }
  720. $option = [];
  721. if (isset($item['limit'])) {
  722. $option['limit'] = (int)$item['limit'];
  723. }
  724. if (isset($item['default'])) {
  725. $option['default'] = $item['default'];
  726. }
  727. //创建伪删除
  728. if ($item['field_type'] === 'addSoftDelete') {
  729. $table->addSoftDelete();
  730. $softDelete = true;
  731. } else if ($item['field_type'] === 'addTimestamps') {
  732. //创建修改和增加时间
  733. $table->addTimestamps();
  734. $timestamps = true;
  735. } else {
  736. $option['comment'] = $item['comment'];
  737. $fieldType = $this->changeTabelRule($item['field_type']);
  738. if (in_array($fieldType, ['text', 'longtext', 'tinytext'])) {
  739. unset($option['limit']);
  740. }
  741. $table->addColumn($item['field'], $this->changeTabelRule($item['field_type']), $option);
  742. }
  743. }
  744. //创建索引
  745. if (!empty($data['tableIndex'])) {
  746. $indexField = $data['tableIndex'];
  747. foreach ($data['tableIndex'] as $item) {
  748. $table->addIndex($item);
  749. }
  750. }
  751. //执行创建
  752. $table->create();
  753. return compact('indexField', 'softDelete', 'timestamps');
  754. }
  755. /**
  756. * 创建文件返回文件路径和内容
  757. * @param string $tableName
  758. * @param string $routeName
  759. * @param bool $isMake
  760. * @param array $options
  761. * @param array $filePath
  762. * @param string $basePath
  763. * @return array[]
  764. * @author 等风来
  765. * @email 136327134@qq.com
  766. * @date 2023/4/7
  767. */
  768. public function makeFile(string $tableName, string $routeName, bool $isMake = false, array $options = [], array $filePath = [], string $basePath = '')
  769. {
  770. $options['fromField'] = is_array($options['fromField']) ? $options['fromField'] : [];
  771. $options['columnField'] = is_array($options['columnField']) ? $options['columnField'] : [];
  772. //生成模型
  773. $model = app()->make(Model::class);
  774. $model->setFilePathName($filePath['model'] ?? '')->setbasePath($basePath)->handle($tableName, $options);
  775. //生成dao
  776. $dao = app()->make(Dao::class);
  777. $dao->setFilePathName($filePath['dao'] ?? '')->setbasePath($basePath)->handle($tableName, [
  778. 'usePath' => $model->getUsePath(),
  779. 'modelName' => $options['modelName'] ?? '',
  780. ]);
  781. //生成service
  782. $service = app()->make(Service::class);
  783. $service->setFilePathName($filePath['service'] ?? '')->setbasePath($basePath)->handle($tableName, [
  784. 'field' => $options['fromField'],
  785. 'key' => $options['key'],
  786. 'usePath' => $dao->getUsePath(),
  787. 'modelName' => $options['modelName'] ?? '',
  788. ]);
  789. //生成验证器
  790. $validate = app()->make(Validate::class);
  791. $validate->setFilePathName($filePath['validate'] ?? '')->setbasePath($basePath)->handle($tableName, [
  792. 'field' => $options['fromField'],
  793. 'modelName' => $options['modelName'] ?? '',
  794. ]);
  795. //生成控制器
  796. $controller = app()->make(Controller::class);
  797. $controller->setFilePathName($filePath['controller'] ?? '')->setbasePath($basePath)->handle($tableName, [
  798. 'usePath' => $service->getUsePath(),
  799. 'modelName' => $options['modelName'] ?? '',
  800. 'validateName' => '\\' . str_replace('/', '\\', $validate->getUsePath()) . 'Validate::class',
  801. 'field' => array_column($options['fromField'], 'field'),
  802. ]);
  803. //生成路由
  804. $route = app()->make(Route::class);
  805. $route->setFilePathName($filePath['route'] ?? '')->setbasePath($basePath)->handle($tableName, [
  806. 'menus' => $options['modelName'] ?? $options['menuName'],
  807. 'route' => $routeName
  808. ]);
  809. //生成前台路由
  810. $viewRouter = app()->make(ViewRouter::class);
  811. $viewRouter->setFilePathName($filePath['router'] ?? '')->setbasePath($basePath)->handle($tableName, [
  812. 'route' => $routeName,
  813. 'menuName' => $options['menuName'],
  814. ]);
  815. //生成前台接口
  816. $viewApi = app()->make(ViewApi::class);
  817. $viewApi->setFilePathName($filePath['api'] ?? '')->setbasePath($basePath)->handle($tableName, [
  818. 'route' => $routeName,
  819. ]);
  820. //生成前台页面
  821. $viewPages = app()->make(ViewPages::class);
  822. $viewPages->setFilePathName($filePath['pages'] ?? '')->setbasePath($basePath)->handle($tableName, [
  823. 'field' => $options['columnField'],
  824. 'route' => $routeName,
  825. 'key' => $options['key'],
  826. 'pathApiJs' => '@/' . str_replace('\\', '/', str_replace([Make::adminTemplatePath(), '.js'], '', $viewApi->getPath())),
  827. ]);
  828. //创建文件
  829. if ($isMake) {
  830. FileService::batchMakeFiles([$model, $validate, $dao, $service, $controller, $route, $viewApi, $viewPages, $viewRouter]);
  831. }
  832. return [
  833. 'controller' => [
  834. 'path' => $this->replace($controller->getPath()),
  835. 'content' => $controller->getContent()
  836. ],
  837. 'model' => [
  838. 'path' => $this->replace($model->getPath()),
  839. 'content' => $model->getContent()
  840. ],
  841. 'dao' => [
  842. 'path' => $this->replace($dao->getPath()),
  843. 'content' => $dao->getContent()
  844. ],
  845. 'route' => [
  846. 'path' => $this->replace($route->getPath()),
  847. 'content' => $route->getContent()
  848. ],
  849. 'service' => [
  850. 'path' => $this->replace($service->getPath()),
  851. 'content' => $service->getContent()
  852. ],
  853. 'validate' => [
  854. 'path' => $this->replace($validate->getPath()),
  855. 'content' => $validate->getContent()
  856. ],
  857. 'router' => [
  858. 'path' => $this->replace($viewRouter->getPath()),
  859. 'content' => $viewRouter->getContent()
  860. ],
  861. 'api' => [
  862. 'path' => $this->replace($viewApi->getPath()),
  863. 'content' => $viewApi->getContent()
  864. ],
  865. 'pages' => [
  866. 'path' => $this->replace($viewPages->getPath()),
  867. 'content' => $viewPages->getContent()
  868. ],
  869. ];
  870. }
  871. protected function replace(string $path)
  872. {
  873. return str_replace([app()->getRootPath(), Make::adminTemplatePath()], '', $path);
  874. }
  875. /**
  876. * @param string $tableName
  877. * @param bool $fullName
  878. * @return string
  879. * @author 等风来
  880. * @email 136327134@qq.com
  881. * @date 2023/4/7
  882. */
  883. public function getTableName(string $tableName, bool $fullName = true)
  884. {
  885. $tablePrefix = config('database.connections.mysql.prefix');
  886. $pattern = '/^' . $tablePrefix . '/i';
  887. return ($fullName ? $tablePrefix : '') . (preg_replace($pattern, '', $tableName));
  888. }
  889. }