SystemCrudServices.php 38 KB

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