SystemCrudServices.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  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. $sql = "ALTER TABLE `$tableName` ADD `$field` $type($limit) NOT NULL DEFAULT '$default' COMMENT '$comment' $after;";
  329. }
  330. return Db::execute($sql);
  331. }
  332. /**
  333. * 删除表字段
  334. * @param string $tableName
  335. * @param string $field
  336. * @return mixed
  337. * @author 等风来
  338. * @email 136327134@qq.com
  339. * @date 2023/4/24
  340. */
  341. protected function deleteAlter(string $tableName, string $field)
  342. {
  343. $tableName = $this->getTableName($tableName);
  344. $field = addslashes($field);
  345. $sql = "ALTER TABLE `$tableName` DROP `$field`";
  346. return Db::execute($sql);
  347. }
  348. /**
  349. * 修改表备注
  350. * @param string $tableName
  351. * @param string $common
  352. * @return mixed
  353. * @author 等风来
  354. * @email 136327134@qq.com
  355. * @date 2023/4/24
  356. */
  357. protected function updateFromCommon(string $tableName, string $common)
  358. {
  359. $tableName = $this->getTableName($tableName);
  360. $common = addslashes($common);
  361. $sql = "ALTER TABLE `$tableName` COMMENT = '$common';";
  362. return Db::execute($sql);
  363. }
  364. /**
  365. * 对比字段变动了更改
  366. * @param string $tableName
  367. * @param array $deleteField
  368. * @param array $tableField
  369. * @author 等风来
  370. * @email 136327134@qq.com
  371. * @date 2023/4/24
  372. */
  373. protected function diffAlter(string $tableName, array $deleteField, array $tableField)
  374. {
  375. $updateAlter = [];
  376. $addAlter = [];
  377. $columns = $this->getColumnNamesList($tableName);
  378. $fieldAll = array_column($columns, 'name');
  379. $prevFiled = $columns[count($columns) - 1]['name'] ?? '';
  380. //对比数据库字段
  381. foreach ($tableField as $item) {
  382. if ($item['primaryKey']) {
  383. continue;
  384. }
  385. //前台新增的字段进行添加
  386. if (!(isset($item['default_field']) &&
  387. isset($item['default_field_type']) &&
  388. isset($item['default_limit']) &&
  389. isset($item['default_comment']) &&
  390. isset($item['default_default']))
  391. ) {
  392. if (!in_array($item['field'], $fieldAll)) {
  393. $addAlter[] = [
  394. 'prev_filed' => $prevFiled,
  395. 'field' => $item['field'],
  396. 'limit' => $item['limit'],
  397. 'type' => $item['field_type'],
  398. 'comment' => $item['comment'],
  399. 'default' => $item['default'],
  400. ];
  401. }
  402. continue;
  403. } else {
  404. //从数据库中新增的字段,并没有记录在表中做兼容处理;
  405. //默认字段没有在数据库中,需要添加字段;
  406. if (!in_array($item['default_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. continue;
  416. }
  417. }
  418. if ($item['default_field'] != $item['field'] && in_array($item['field_type'], ['addTimestamps', 'addSoftDelete'])) {
  419. throw new AdminException($item['field'] . '字段不允许被更改');
  420. }
  421. //数据库表存在的,字段,并且被修改
  422. if ($item['default_field'] != $item['field'] ||
  423. $item['default_field_type'] != $item['field_type'] ||
  424. $item['default_limit'] != $item['limit'] ||
  425. $item['default_comment'] != $item['comment'] ||
  426. $item['default_default'] != $item['default']) {
  427. $updateAlter[] = [
  428. 'default_field' => $item['default_field'],
  429. 'field' => $item['field'],
  430. 'limit' => $item['limit'],
  431. 'type' => $item['field_type'],
  432. 'comment' => $item['comment'],
  433. 'default' => $item['default'],
  434. ];
  435. }
  436. }
  437. //更新数据库字段
  438. foreach ($updateAlter as $item) {
  439. $this->updateAlter($tableName, $item['default_field'], $item['field'], $item['type'], $item['limit'], $item['default'], $item['comment']);
  440. }
  441. //添加字段
  442. foreach ($addAlter as $item) {
  443. $this->addAlter($tableName, $item['field'], $item['prev_filed'], $item['type'], $item['limit'], $item['default'], $item['comment']);
  444. }
  445. //删除多余字段
  446. foreach ($deleteField as $item) {
  447. $this->deleteAlter($tableName, $item);
  448. }
  449. }
  450. /**
  451. * 创建
  452. * @param array $data
  453. * @return mixed
  454. * @author 等风来
  455. * @email 136327134@qq.com
  456. * @date 2023/4/11
  457. */
  458. public function createCrud(int $id, array $data)
  459. {
  460. $tableName = $data['tableName'];
  461. $tableField = $this->valueReplace($data['tableField']);
  462. $filePath = $this->valueReplace($data['filePath']);
  463. $modelName = !empty($data['modelName']) ? $data['modelName'] : $tableName;
  464. $tableComment = !empty($data['tableComment']) ? $data['tableComment'] : $modelName;
  465. //检测是否为系统表
  466. if (in_array($tableName, self::NOT_CRUD_TABANAME)) {
  467. throw new AdminException(500041);
  468. }
  469. $data['softDelete'] = false;
  470. $tableInfo = null;
  471. //先检查表存在则
  472. if ($id) {
  473. $this->updateFromCommon($tableName, $tableComment);
  474. //读取数据库表
  475. $tableInfo = $this->getTableInfo($tableName);
  476. if ($tableInfo) {
  477. //对比字段进行更新/删除字段
  478. $this->diffAlter($tableName, $data['deleteField'], $tableField);
  479. }
  480. } else {
  481. if ($this->dao->count(['table_name' => $tableName])) {
  482. throw new AdminException('表已经被生成过,请在列表中进行修改');
  483. }
  484. }
  485. //创建数据库
  486. $tableCreateInfo = null;
  487. if ($tableField && (!$data['isTable'] || !$tableInfo)) {
  488. $tableCreateInfo = $this->makeDatebase($tableName, $tableComment, $tableField);
  489. if ($tableCreateInfo['softDelete']) {
  490. $data['softDelete'] = true;
  491. }
  492. }
  493. //读取字段
  494. //读取数据库字段信息
  495. $tableInfo = $this->getTableInfo($tableName);
  496. //获取主键
  497. foreach ($tableField as $value) {
  498. if ($value['primaryKey']) {
  499. $data['key'] = $value['field'];
  500. break;
  501. }
  502. }
  503. $routeName = 'crud/' . Str::snake($tableName);
  504. $uniqueAuth = Str::snake($tableName) . '-crud-list-index';
  505. //增加保存的绝对路径
  506. foreach ($filePath as $k => $i) {
  507. if (in_array($k, ['pages', 'router', 'api'])) {
  508. $filePath[$k] = Make::adminTemplatePath() . $i;
  509. } else {
  510. $filePath[$k] = app()->getRootPath() . $i;
  511. }
  512. }
  513. //创建菜单
  514. if (!$data['menuName']) {
  515. $data['menuName'] = $tableName;
  516. }
  517. $dataMenu = [
  518. 'pid' => $data['pid'],
  519. 'menu_name' => $data['menuName'],
  520. 'menu_path' => '/' . $routeName,
  521. 'auth_type' => 1,
  522. 'is_show' => 1,
  523. 'is_show_path' => 1,
  524. 'is_del' => 0,
  525. 'unique_auth' => $uniqueAuth,
  526. 'is_header' => $data['pid'] ? 0 : 1,
  527. ];
  528. $crudInfo = null;
  529. if ($id) {
  530. $crudInfo = $this->dao->get($id);
  531. }
  532. $res = $this->transaction(function () use ($tableComment, $tableCreateInfo, $crudInfo, $modelName, $filePath, $tableName, $routeName, $data, $dataMenu) {
  533. $routeService = app()->make(SystemRouteServices::class);
  534. $meunService = app()->make(SystemMenusServices::class);
  535. //修改菜单名称
  536. if ($crudInfo) {
  537. //菜单存在的时候进行修改
  538. if ($crudInfo->menu_id && $meunService->value(['id' => [$crudInfo->menu_id]], 'id')) {
  539. $meunService->update($crudInfo->menu_id, $dataMenu);
  540. $menuInfo = (object)['id' => $crudInfo->menu_id];
  541. } else {
  542. $menuInfo = $meunService->save($dataMenu);
  543. }
  544. //删除掉添加的路由权限
  545. if ($crudInfo->route_ids) {
  546. $routeService->deleteRoutes($crudInfo->route_ids);
  547. }
  548. //删除掉权限路由
  549. if ($crudInfo->menu_ids) {
  550. app()->make(SystemMenusServices::class)->deleteMenus($crudInfo->menu_ids);
  551. }
  552. } else {
  553. $menuInfo = $meunService->save($dataMenu);
  554. }
  555. //写入路由权限
  556. $cateId = app()->make(SystemRouteServices::class)->topCateId('adminapi', 'CRUD');
  557. $ruleData = [
  558. [
  559. 'path' => $routeName,
  560. 'method' => 'GET',
  561. 'name' => $modelName . '列表接口',
  562. 'app_name' => 'adminapi',
  563. 'cate_id' => $cateId,
  564. 'unique_auth' => '',
  565. 'add_time' => date('Y-m-d H:i:s')
  566. ],
  567. [
  568. 'path' => $routeName . '/create',
  569. 'method' => 'GET',
  570. 'name' => $modelName . '获取创建表单接口',
  571. 'app_name' => 'adminapi',
  572. 'cate_id' => $cateId,
  573. 'unique_auth' => Str::snake($tableName) . '-add',
  574. 'add_time' => date('Y-m-d H:i:s')
  575. ],
  576. [
  577. 'path' => $routeName,
  578. 'method' => 'POST',
  579. 'name' => $modelName . '保存接口',
  580. 'app_name' => 'adminapi',
  581. 'cate_id' => $cateId,
  582. 'unique_auth' => '',
  583. 'add_time' => date('Y-m-d H:i:s')
  584. ],
  585. [
  586. 'path' => $routeName . '/<id>/edit',
  587. 'method' => 'GET',
  588. 'name' => $modelName . '获取修改表单接口',
  589. 'app_name' => 'adminapi',
  590. 'cate_id' => $cateId,
  591. 'unique_auth' => '',
  592. 'add_time' => date('Y-m-d H:i:s')
  593. ],
  594. [
  595. 'path' => $routeName . '/<id>',
  596. 'method' => 'PUT',
  597. 'name' => $modelName . '修改接口',
  598. 'app_name' => 'adminapi',
  599. 'cate_id' => $cateId,
  600. 'unique_auth' => '',
  601. 'add_time' => date('Y-m-d H:i:s')
  602. ],
  603. [
  604. 'path' => $routeName . '/<id>',
  605. 'method' => 'DELETE',
  606. 'name' => $modelName . '删除接口',
  607. 'app_name' => 'adminapi',
  608. 'cate_id' => $cateId,
  609. 'unique_auth' => '',
  610. 'add_time' => date('Y-m-d H:i:s')
  611. ],
  612. ];
  613. $routeList = $routeService->saveAll($ruleData);
  614. $routeIds = array_column($routeList->toArray(), 'id');
  615. //记录权限加入菜单表
  616. $menuData = [];
  617. foreach ($ruleData as $item) {
  618. $menuData[] = [
  619. 'pid' => $menuInfo->id ?: 0,
  620. 'methods' => $item['method'],
  621. 'api_url' => $item['path'],
  622. 'unique_auth' => $item['unique_auth'],
  623. 'menu_name' => $item['name'],
  624. 'is_del' => 0,
  625. 'auth_type' => 2,
  626. ];
  627. }
  628. $menus = app()->make(SystemMenusServices::class)->saveAll($menuData);
  629. $menuIds = array_column($menus->toArray(), 'id');
  630. //生成文件
  631. $make = $this->makeFile($tableName, $routeName, true, $data, $filePath);
  632. $makePath = [];
  633. foreach ($make as $key => $item) {
  634. $makePath[$key] = $item['path'];
  635. }
  636. if ($tableCreateInfo && isset($tableCreateInfo['table']) && $tableCreateInfo['table'] instanceof Table) {
  637. //创建数据库
  638. $tableCreateInfo['table']->create();
  639. }
  640. $crudDate = [
  641. 'pid' => $data['pid'],
  642. 'name' => $data['menuName'],
  643. 'model_name' => $data['modelName'],
  644. 'table_name' => $tableName,
  645. 'table_comment' => $tableComment,
  646. 'table_collation' => self::TABLR_COLLATION,
  647. 'field' => json_encode($data),//提交的数据
  648. 'menu_ids' => json_encode($menuIds),//生成的菜单id
  649. 'menu_id' => $menuInfo->id,//生成的菜单id
  650. 'make_path' => json_encode($makePath),
  651. 'route_ids' => json_encode($routeIds),
  652. ];
  653. if ($crudInfo) {
  654. $res = $this->dao->update($crudInfo->id, $crudDate);
  655. } else {
  656. $crudDate['add_time'] = time();
  657. //记录crud生成
  658. $res = $this->dao->save($crudDate);
  659. }
  660. return $res;
  661. });
  662. return $res->toArray();
  663. }
  664. /**
  665. * 获取数据库配置
  666. * @return array
  667. */
  668. protected function getDbConfig(): array
  669. {
  670. $default = app()->config->get('database.default');
  671. $config = app()->config->get("database.connections.{$default}");
  672. if (0 == $config['deploy']) {
  673. $dbConfig = [
  674. 'adapter' => $config['type'],
  675. 'host' => $config['hostname'],
  676. 'name' => $config['database'],
  677. 'user' => $config['username'],
  678. 'pass' => $config['password'],
  679. 'port' => $config['hostport'],
  680. 'charset' => $config['charset'],
  681. 'table_prefix' => $config['prefix'],
  682. ];
  683. } else {
  684. $dbConfig = [
  685. 'adapter' => explode(',', $config['type'])[0],
  686. 'host' => explode(',', $config['hostname'])[0],
  687. 'name' => explode(',', $config['database'])[0],
  688. 'user' => explode(',', $config['username'])[0],
  689. 'pass' => explode(',', $config['password'])[0],
  690. 'port' => explode(',', $config['hostport'])[0],
  691. 'charset' => explode(',', $config['charset'])[0],
  692. 'table_prefix' => explode(',', $config['prefix'])[0],
  693. ];
  694. }
  695. $table = app()->config->get('database.migration_table', 'migrations');
  696. $dbConfig['default_migration_table'] = $dbConfig['table_prefix'] . $table;
  697. return $dbConfig;
  698. }
  699. public function getAdapter()
  700. {
  701. $options = $this->getDbConfig();
  702. $adapter = AdapterFactory::instance()->getAdapter($options['adapter'], $options);
  703. if ($adapter->hasOption('table_prefix') || $adapter->hasOption('table_suffix')) {
  704. $adapter = AdapterFactory::instance()->getWrapper('prefix', $adapter);
  705. }
  706. return $adapter;
  707. }
  708. /**
  709. * 创建数据库
  710. * @param string $tableName
  711. * @param string $tableComment
  712. * @param array $tableField
  713. * @return array
  714. * @author 等风来
  715. * @email 136327134@qq.com
  716. * @date 2023/4/7
  717. */
  718. public function makeDatebase(string $tableName, string $tableComment, array $tableField = [], string $collation = self::TABLR_COLLATION)
  719. {
  720. $timestampsField = [];
  721. $softDelete = false;
  722. $timestamps = false;
  723. $indexField = [];
  724. //创建表
  725. $table = new Table($tableName, ['comment' => $tableComment, 'collation' => $collation], $this->getAdapter());
  726. //创建字段
  727. foreach ($tableField as $item) {
  728. if (isset($item['primaryKey']) && $item['primaryKey']) {
  729. continue;
  730. }
  731. $option = [];
  732. if (isset($item['limit'])) {
  733. $option['limit'] = (int)$item['limit'];
  734. }
  735. if (isset($item['default'])) {
  736. $option['default'] = $item['default'];
  737. }
  738. //创建伪删除
  739. if ($item['field_type'] === 'addSoftDelete') {
  740. $table->addSoftDelete();
  741. $softDelete = true;
  742. } else if ($item['field_type'] == 'timestamp' &&
  743. ($item['field'] === 'create_time' || $item['field'] === 'update_time')) {
  744. $timestampsField[] = $item;
  745. } else {
  746. $option['comment'] = $item['comment'];
  747. $fieldType = $this->changeTabelRule($item['field_type']);
  748. if (in_array($fieldType, ['text', 'longtext', 'tinytext'])) {
  749. unset($option['limit']);
  750. }
  751. //判断字段类型
  752. if ($fieldType == 'boolean' && isset($option['default']) && $option['default'] === '') {
  753. unset($option['default']);
  754. }
  755. $table->addColumn($item['field'], $this->changeTabelRule($item['field_type']), $option);
  756. }
  757. }
  758. //创建索引
  759. if (!empty($data['tableIndex'])) {
  760. $indexField = $data['tableIndex'];
  761. foreach ($data['tableIndex'] as $item) {
  762. $table->addIndex($item);
  763. }
  764. }
  765. //如果是成对出现的create_time和update_time就直接增加修改和添加时间
  766. if (count($timestampsField) == 2) {
  767. //创建修改和增加时间
  768. $table->addTimestamps();
  769. $timestamps = true;
  770. } else {
  771. //如果是一个数组,增加一列
  772. foreach ($timestampsField as $item) {
  773. $option['comment'] = $item['comment'];
  774. $table->addColumn($item['field'], $this->changeTabelRule($item['field_type']), $option);
  775. }
  776. }
  777. return compact('indexField', 'softDelete', 'timestamps', 'table');
  778. }
  779. /**
  780. * 创建文件返回文件路径和内容
  781. * @param string $tableName
  782. * @param string $routeName
  783. * @param bool $isMake
  784. * @param array $options
  785. * @param array $filePath
  786. * @param string $basePath
  787. * @return array[]
  788. * @author 等风来
  789. * @email 136327134@qq.com
  790. * @date 2023/4/7
  791. */
  792. public function makeFile(string $tableName, string $routeName, bool $isMake = false, array $options = [], array $filePath = [], string $basePath = '')
  793. {
  794. $options['fromField'] = is_array($options['fromField']) ? $options['fromField'] : [];
  795. $options['columnField'] = is_array($options['columnField']) ? $options['columnField'] : [];
  796. //生成模型
  797. $model = app()->make(Model::class);
  798. $model->setFilePathName($filePath['model'] ?? '')->setbasePath($basePath)->handle($tableName, $options);
  799. //生成dao
  800. $dao = app()->make(Dao::class);
  801. $dao->setFilePathName($filePath['dao'] ?? '')->setbasePath($basePath)->handle($tableName, [
  802. 'usePath' => $model->getUsePath(),
  803. 'modelName' => $options['modelName'] ?? '',
  804. ]);
  805. //生成service
  806. $service = app()->make(Service::class);
  807. $service->setFilePathName($filePath['service'] ?? '')->setbasePath($basePath)->handle($tableName, [
  808. 'field' => $options['fromField'],
  809. 'key' => $options['key'],
  810. 'usePath' => $dao->getUsePath(),
  811. 'modelName' => $options['modelName'] ?? '',
  812. ]);
  813. //生成验证器
  814. $validate = app()->make(Validate::class);
  815. $validate->setFilePathName($filePath['validate'] ?? '')->setbasePath($basePath)->handle($tableName, [
  816. 'field' => $options['fromField'],
  817. 'modelName' => $options['modelName'] ?? '',
  818. ]);
  819. //生成控制器
  820. $controller = app()->make(Controller::class);
  821. $controller->setFilePathName($filePath['controller'] ?? '')->setbasePath($basePath)->handle($tableName, [
  822. 'usePath' => $service->getUsePath(),
  823. 'modelName' => $options['modelName'] ?? '',
  824. 'validateName' => '\\' . str_replace('/', '\\', $validate->getUsePath()) . 'Validate::class',
  825. 'field' => array_column($options['fromField'], 'field'),
  826. ]);
  827. //生成路由
  828. $route = app()->make(Route::class);
  829. $route->setFilePathName($filePath['route'] ?? '')->setbasePath($basePath)->handle($tableName, [
  830. 'menus' => $options['modelName'] ?? $options['menuName'],
  831. 'route' => $routeName
  832. ]);
  833. //生成前台路由
  834. $viewRouter = app()->make(ViewRouter::class);
  835. $viewRouter->setFilePathName($filePath['router'] ?? '')->setbasePath($basePath)->handle($tableName, [
  836. 'route' => $routeName,
  837. 'menuName' => $options['menuName'],
  838. ]);
  839. //生成前台接口
  840. $viewApi = app()->make(ViewApi::class);
  841. $viewApi->setFilePathName($filePath['api'] ?? '')->setbasePath($basePath)->handle($tableName, [
  842. 'route' => $routeName,
  843. ]);
  844. //生成前台页面
  845. $viewPages = app()->make(ViewPages::class);
  846. $viewPages->setFilePathName($filePath['pages'] ?? '')->setbasePath($basePath)->handle($tableName, [
  847. 'field' => $options['columnField'],
  848. 'route' => $routeName,
  849. 'key' => $options['key'],
  850. 'pathApiJs' => '@/' . str_replace('\\', '/', str_replace([Make::adminTemplatePath(), '.js'], '', $viewApi->getPath())),
  851. ]);
  852. //创建文件
  853. if ($isMake) {
  854. FileService::batchMakeFiles([$model, $validate, $dao, $service, $controller, $route, $viewApi, $viewPages, $viewRouter]);
  855. }
  856. return [
  857. 'controller' => [
  858. 'path' => $this->replace($controller->getPath()),
  859. 'content' => $controller->getContent()
  860. ],
  861. 'model' => [
  862. 'path' => $this->replace($model->getPath()),
  863. 'content' => $model->getContent()
  864. ],
  865. 'dao' => [
  866. 'path' => $this->replace($dao->getPath()),
  867. 'content' => $dao->getContent()
  868. ],
  869. 'route' => [
  870. 'path' => $this->replace($route->getPath()),
  871. 'content' => $route->getContent()
  872. ],
  873. 'service' => [
  874. 'path' => $this->replace($service->getPath()),
  875. 'content' => $service->getContent()
  876. ],
  877. 'validate' => [
  878. 'path' => $this->replace($validate->getPath()),
  879. 'content' => $validate->getContent()
  880. ],
  881. 'router' => [
  882. 'path' => $this->replace($viewRouter->getPath()),
  883. 'content' => $viewRouter->getContent()
  884. ],
  885. 'api' => [
  886. 'path' => $this->replace($viewApi->getPath()),
  887. 'content' => $viewApi->getContent()
  888. ],
  889. 'pages' => [
  890. 'path' => $this->replace($viewPages->getPath()),
  891. 'content' => $viewPages->getContent()
  892. ],
  893. ];
  894. }
  895. protected function replace(string $path)
  896. {
  897. return str_replace([app()->getRootPath(), Make::adminTemplatePath()], '', $path);
  898. }
  899. /**
  900. * @param string $tableName
  901. * @param bool $fullName
  902. * @return string
  903. * @author 等风来
  904. * @email 136327134@qq.com
  905. * @date 2023/4/7
  906. */
  907. public function getTableName(string $tableName, bool $fullName = true)
  908. {
  909. $tablePrefix = config('database.connections.mysql.prefix');
  910. $pattern = '/^' . $tablePrefix . '/i';
  911. return ($fullName ? $tablePrefix : '') . (preg_replace($pattern, '', $tableName));
  912. }
  913. }