SystemCrudServices.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  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' => '',
  140. 'label' => '请选择',
  141. ],
  142. [
  143. 'value' => 'input',
  144. 'label' => '输入框',
  145. ],
  146. [
  147. 'value' => 'number',
  148. 'label' => '数字输入框',
  149. ],
  150. [
  151. 'value' => 'textarea',
  152. 'label' => '多行文本框',
  153. ],
  154. [
  155. 'value' => 'dateTime',
  156. 'label' => '单选日期时间',
  157. ],
  158. // [
  159. // 'value' => 'dateTimeRange',
  160. // 'label' => '日期时间区间选择',
  161. // ],
  162. [
  163. 'value' => 'checkbox',
  164. 'label' => '多选框',
  165. ],
  166. [
  167. 'value' => 'radio',
  168. 'label' => '单选框',
  169. ],
  170. [
  171. 'value' => 'select',
  172. 'label' => '下拉框',
  173. ],
  174. [
  175. 'value' => 'frameImageOne',
  176. 'label' => '单图选择'
  177. ],
  178. [
  179. 'value' => 'frameImages',
  180. 'label' => '多图选择'
  181. ],
  182. ],
  183. 'rule' => $rule
  184. ];
  185. }
  186. /**
  187. * 改变数据库类型
  188. * @param string $type
  189. * @return string
  190. * @author 等风来
  191. * @email 136327134@qq.com
  192. * @date 2023/4/13
  193. */
  194. public function changeTabelRule(string $type)
  195. {
  196. if (!in_array($type, $this->getTabelRule()['types'])) {
  197. throw new AdminException(500047);
  198. }
  199. return $this->getTabelRule()['rule'][$type] ?? $type;
  200. }
  201. /**
  202. * @param string $tableName
  203. * @return mixed
  204. * @author 等风来
  205. * @email 136327134@qq.com
  206. * @date 2023/4/14
  207. */
  208. public function getTableInfo(string $tableName)
  209. {
  210. $sql = 'SELECT * FROM `information_schema`.`TABLES` WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?';
  211. $tableInfo = Db::query($sql, [config('database.connections.mysql.database'), $this->getTableName($tableName)]);
  212. return $tableInfo[0] ?? [];
  213. }
  214. /**
  215. * 获取表字段
  216. * @param string $tableName
  217. * @return mixed
  218. * @author 等风来
  219. * @email 136327134@qq.com
  220. * @date 2023/4/7
  221. */
  222. public function getColumnNamesList(string $tableName)
  223. {
  224. $sql = 'SELECT * FROM `information_schema`.`columns` WHERE TABLE_SCHEMA = ? AND table_name = ? ORDER BY ORDINAL_POSITION';
  225. $column = Db::query($sql, [config('database.connections.mysql.database'), $this->getTableName($tableName)]);
  226. $columns = [];
  227. foreach ($column as $item) {
  228. $column = [
  229. 'name' => $item['COLUMN_NAME'],
  230. 'type' => $item['DATA_TYPE'],
  231. 'dataType' => stripos($item['COLUMN_TYPE'], '(') !== false ? substr_replace($item['COLUMN_TYPE'], '', stripos($item['COLUMN_TYPE'], ')') + 1) : $item['COLUMN_TYPE'],
  232. 'default' => $item['COLUMN_DEFAULT'],
  233. 'null' => $item['IS_NULLABLE'] == 'YES',
  234. 'primaryKey' => $item['COLUMN_KEY'] == 'PRI',
  235. 'unsigned' => (bool)stripos($item['COLUMN_TYPE'], 'unsigned'),
  236. 'autoIncrement' => stripos($item['EXTRA'], 'auto_increment') !== false,
  237. 'comment' => $item['COLUMN_COMMENT'],
  238. 'limit' => $item['CHARACTER_MAXIMUM_LENGTH'] ?: $item['NUMERIC_PRECISION'],
  239. ];
  240. $columns[$item['COLUMN_NAME']] = $column;
  241. }
  242. return $columns;
  243. }
  244. /**
  245. * @param array $data
  246. * @return array
  247. * @author 等风来
  248. * @email 136327134@qq.com
  249. * @date 2023/4/12
  250. */
  251. public function valueReplace(array $data)
  252. {
  253. $replace = ['phar://'];
  254. $newData = [];
  255. foreach ($data as $key => $item) {
  256. if (is_array($item)) {
  257. $item = $this->valueReplace($item);
  258. } else {
  259. $item = str_replace($replace, '', $item);
  260. }
  261. $newData[str_replace($replace, '', $key)] = $item;
  262. }
  263. return $newData;
  264. }
  265. /**
  266. * 更新表字段
  267. * @param string $tableName
  268. * @param string $field
  269. * @param string $changeFiled
  270. * @param string $type
  271. * @param string $limit
  272. * @param string $default
  273. * @param string $comment
  274. * @param array $options
  275. * @return mixed
  276. * @author 等风来
  277. * @email 136327134@qq.com
  278. * @date 2023/4/24
  279. */
  280. protected function updateAlter(string $tableName, string $field, string $changeFiled, string $type, $limit = '', string $default = '', string $comment = '', array $options = [])
  281. {
  282. $tableName = $this->getTableName($tableName);
  283. $comment = addslashes($comment);
  284. $field = addslashes($field);
  285. $changeFiled = addslashes($changeFiled);
  286. $type = addslashes($type);
  287. $default = addslashes($default);
  288. if (in_array(strtolower($type), ['text', 'longtext', 'tinytext'])) {
  289. $sql = "ALTER TABLE `$tableName` CHANGE `$field` `$changeFiled` $type CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '$comment';";
  290. } else {
  291. $sql = "ALTER TABLE `$tableName` CHANGE `$field` `$changeFiled` $type($limit) NOT NULL DEFAULT '$default' COMMENT '$comment';";
  292. }
  293. return Db::execute($sql);
  294. }
  295. /**
  296. * 添加字段
  297. * @param string $tableName
  298. * @param string $field
  299. * @param string $prevFiled
  300. * @param string $type
  301. * @param string $limit
  302. * @param string $default
  303. * @param string $comment
  304. * @param array $options
  305. * @return mixed
  306. * @author 等风来
  307. * @email 136327134@qq.com
  308. * @date 2023/4/24
  309. */
  310. public function addAlter(string $tableName, string $field, string $prevFiled, string $type, $limit = '', string $default = '', string $comment = '', array $options = [])
  311. {
  312. $tableName = $this->getTableName($tableName);
  313. $comment = addslashes($comment);
  314. $field = addslashes($field);
  315. $prevFiled = addslashes($prevFiled);
  316. $type = addslashes($type);
  317. $default = addslashes($default);
  318. if ($prevFiled) {
  319. $after = "AFTER `$prevFiled`";
  320. } else {
  321. $after = "";
  322. }
  323. if (in_array(strtolower($type), ['text', 'longtext', 'tinytext'])) {
  324. $sql = "ALTER TABLE `$tableName` ADD `$field` $type NULL COMMENT '$comment' $after;";
  325. } else {
  326. $sql = "ALTER TABLE `$tableName` ADD `$field` $type($limit) NOT NULL DEFAULT '$default' COMMENT '$comment' $after;";
  327. }
  328. return Db::execute($sql);
  329. }
  330. /**
  331. * 删除表字段
  332. * @param string $tableName
  333. * @param string $field
  334. * @return mixed
  335. * @author 等风来
  336. * @email 136327134@qq.com
  337. * @date 2023/4/24
  338. */
  339. protected function deleteAlter(string $tableName, string $field)
  340. {
  341. $tableName = $this->getTableName($tableName);
  342. $field = addslashes($field);
  343. $sql = "ALTER TABLE `$tableName` DROP `$field`";
  344. return Db::execute($sql);
  345. }
  346. /**
  347. * 修改表备注
  348. * @param string $tableName
  349. * @param string $common
  350. * @return mixed
  351. * @author 等风来
  352. * @email 136327134@qq.com
  353. * @date 2023/4/24
  354. */
  355. protected function updateFromCommon(string $tableName, string $common)
  356. {
  357. $tableName = $this->getTableName($tableName);
  358. $common = addslashes($common);
  359. $sql = "ALTER TABLE `$tableName` COMMENT = '$common';";
  360. return Db::execute($sql);
  361. }
  362. /**
  363. * 对比字段变动了更改
  364. * @param string $tableName
  365. * @param array $deleteField
  366. * @param array $tableField
  367. * @author 等风来
  368. * @email 136327134@qq.com
  369. * @date 2023/4/24
  370. */
  371. protected function diffAlter(string $tableName, array $deleteField, array $tableField)
  372. {
  373. $updateAlter = [];
  374. $addAlter = [];
  375. $columns = $this->getColumnNamesList($tableName);
  376. $fieldAll = array_column($columns, 'name');
  377. $prevFiled = $columns[count($columns) - 1]['name'] ?? '';
  378. //对比数据库字段
  379. foreach ($tableField as $item) {
  380. if ($item['primaryKey']) {
  381. continue;
  382. }
  383. //前台新增的字段进行添加
  384. if (!(isset($item['default_field']) &&
  385. isset($item['default_field_type']) &&
  386. isset($item['default_limit']) &&
  387. isset($item['default_comment']) &&
  388. isset($item['default_default']))
  389. ) {
  390. if (!in_array($item['field'], $fieldAll)) {
  391. $addAlter[] = [
  392. 'prev_filed' => $prevFiled,
  393. 'field' => $item['field'],
  394. 'limit' => $item['limit'],
  395. 'type' => $item['field_type'],
  396. 'comment' => $item['comment'],
  397. 'default' => $item['default'],
  398. ];
  399. }
  400. continue;
  401. } else {
  402. //默认字段没有在数据库中,需要添加字段
  403. if (!in_array($item['default_field'], $fieldAll)) {
  404. $addAlter[] = [
  405. 'prev_filed' => $prevFiled,
  406. 'field' => $item['field'],
  407. 'limit' => $item['limit'],
  408. 'type' => $item['field_type'],
  409. 'comment' => $item['comment'],
  410. 'default' => $item['default'],
  411. ];
  412. continue;
  413. }
  414. }
  415. if ($item['default_field'] != $item['field'] && in_array($item['field_type'], ['addTimestamps', 'addSoftDelete'])) {
  416. throw new AdminException($item['field'] . '字段不允许被更改');
  417. }
  418. //数据库表存在的,字段,并且被修改
  419. if ($item['default_field'] != $item['field'] ||
  420. $item['default_field_type'] != $item['field_type'] ||
  421. $item['default_limit'] != $item['limit'] ||
  422. $item['default_comment'] != $item['comment'] ||
  423. $item['default_default'] != $item['default']) {
  424. $updateAlter[] = [
  425. 'default_field' => $item['default_field'],
  426. 'field' => $item['field'],
  427. 'limit' => $item['limit'],
  428. 'type' => $item['field_type'],
  429. 'comment' => $item['comment'],
  430. 'default' => $item['default'],
  431. ];
  432. }
  433. }
  434. //更新数据库字段
  435. foreach ($updateAlter as $item) {
  436. $this->updateAlter($tableName, $item['default_field'], $item['field'], $item['type'], $item['limit'], $item['default'], $item['comment']);
  437. }
  438. //添加字段
  439. foreach ($addAlter as $item) {
  440. $this->addAlter($tableName, $item['field'], $item['prev_filed'], $item['type'], $item['limit'], $item['default'], $item['comment']);
  441. }
  442. //删除多余字段
  443. foreach ($deleteField as $item) {
  444. $this->deleteAlter($tableName, $item);
  445. }
  446. }
  447. /**
  448. * 创建
  449. * @param array $data
  450. * @return mixed
  451. * @author 等风来
  452. * @email 136327134@qq.com
  453. * @date 2023/4/11
  454. */
  455. public function createCrud(int $id, array $data)
  456. {
  457. $tableName = $data['tableName'];
  458. $tableField = $this->valueReplace($data['tableField']);
  459. $filePath = $this->valueReplace($data['filePath']);
  460. $modelName = !empty($data['modelName']) ? $data['modelName'] : $tableName;
  461. $tableComment = !empty($data['tableComment']) ? $data['tableComment'] : $modelName;
  462. //检测是否为系统表
  463. if (in_array($tableName, self::NOT_CRUD_TABANAME)) {
  464. throw new AdminException(500044);
  465. }
  466. $data['softDelete'] = false;
  467. //先检查表存在则
  468. if ($id) {
  469. $this->updateFromCommon($tableName, $tableComment);
  470. //删除数据库表
  471. $tableInfo = $this->getTableInfo($tableName);
  472. if ($tableInfo) {
  473. //对比字段进行更新/删除字段
  474. $this->diffAlter($tableName, $data['deleteField'], $tableField);
  475. }
  476. } else {
  477. if ($this->dao->count(['table_name' => $tableName])) {
  478. throw new AdminException('表已经被生成过,请在列表中进行修改');
  479. }
  480. }
  481. //创建数据库
  482. $tableCreateInfo = null;
  483. if ($tableField && (!$data['isTable'] || !$tableInfo)) {
  484. $tableCreateInfo = $this->makeDatebase($tableName, $tableComment, $tableField);
  485. if ($tableCreateInfo['softDelete']) {
  486. $data['softDelete'] = true;
  487. }
  488. }
  489. //读取表结构
  490. $column = $this->getColumnNamesList($tableName);
  491. if (!$column) {
  492. throw new AdminException(500049, ['_name' => $tableName]);
  493. }
  494. //读取字段
  495. //读取数据库字段信息
  496. $tableInfo = $this->getTableInfo($tableName);
  497. //获取主键
  498. foreach ($column as $value) {
  499. if ($value['primaryKey']) {
  500. $data['key'] = $value['name'];
  501. break;
  502. }
  503. }
  504. $routeName = 'crud/' . Str::snake($tableName);
  505. $uniqueAuth = Str::snake($tableName) . '-crud-list-index';
  506. //增加保存的绝对路径
  507. foreach ($filePath as $k => $i) {
  508. if (in_array($k, ['pages', 'router', 'api'])) {
  509. $filePath[$k] = Make::adminTemplatePath() . $i;
  510. } else {
  511. $filePath[$k] = app()->getRootPath() . $i;
  512. }
  513. }
  514. //创建菜单
  515. if (!$data['menuName']) {
  516. $data['menuName'] = $tableName;
  517. }
  518. $dataMenu = [
  519. 'pid' => $data['pid'],
  520. 'menu_name' => $data['menuName'],
  521. 'menu_path' => '/' . $routeName,
  522. 'auth_type' => 1,
  523. 'is_show' => 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 ($tableCreateInfo, $crudInfo, $tableInfo, $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. $tableInfo = $this->getTableInfo($tableName);
  640. }
  641. $crudDate = [
  642. 'pid' => $data['pid'],
  643. 'name' => $data['menuName'],
  644. 'model_name' => $data['modelName'],
  645. 'table_name' => $tableName,
  646. 'table_comment' => $tableInfo['TABLE_COMMENT'] ?? '',
  647. 'table_collation' => $tableInfo['TABLE_COLLATION'] ?? '',
  648. 'field' => json_encode($data),//提交的数据
  649. 'menu_ids' => json_encode($menuIds),//生成的菜单id
  650. 'menu_id' => $menuInfo->id,//生成的菜单id
  651. 'make_path' => json_encode($makePath),
  652. 'route_ids' => json_encode($routeIds),
  653. ];
  654. if ($crudInfo) {
  655. $res = $this->dao->update($crudInfo->id, $crudDate);
  656. } else {
  657. $crudDate['add_time'] = time();
  658. //记录crud生成
  659. $res = $this->dao->save($crudDate);
  660. }
  661. return $res;
  662. });
  663. return $res->toArray();
  664. }
  665. /**
  666. * 获取数据库配置
  667. * @return array
  668. */
  669. protected function getDbConfig(): array
  670. {
  671. $default = app()->config->get('database.default');
  672. $config = app()->config->get("database.connections.{$default}");
  673. if (0 == $config['deploy']) {
  674. $dbConfig = [
  675. 'adapter' => $config['type'],
  676. 'host' => $config['hostname'],
  677. 'name' => $config['database'],
  678. 'user' => $config['username'],
  679. 'pass' => $config['password'],
  680. 'port' => $config['hostport'],
  681. 'charset' => $config['charset'],
  682. 'table_prefix' => $config['prefix'],
  683. ];
  684. } else {
  685. $dbConfig = [
  686. 'adapter' => explode(',', $config['type'])[0],
  687. 'host' => explode(',', $config['hostname'])[0],
  688. 'name' => explode(',', $config['database'])[0],
  689. 'user' => explode(',', $config['username'])[0],
  690. 'pass' => explode(',', $config['password'])[0],
  691. 'port' => explode(',', $config['hostport'])[0],
  692. 'charset' => explode(',', $config['charset'])[0],
  693. 'table_prefix' => explode(',', $config['prefix'])[0],
  694. ];
  695. }
  696. $table = app()->config->get('database.migration_table', 'migrations');
  697. $dbConfig['default_migration_table'] = $dbConfig['table_prefix'] . $table;
  698. return $dbConfig;
  699. }
  700. public function getAdapter()
  701. {
  702. $options = $this->getDbConfig();
  703. $adapter = AdapterFactory::instance()->getAdapter($options['adapter'], $options);
  704. if ($adapter->hasOption('table_prefix') || $adapter->hasOption('table_suffix')) {
  705. $adapter = AdapterFactory::instance()->getWrapper('prefix', $adapter);
  706. }
  707. return $adapter;
  708. }
  709. /**
  710. * 创建数据库
  711. * @param string $tableName
  712. * @param string $tableComment
  713. * @param array $tableField
  714. * @return array
  715. * @author 等风来
  716. * @email 136327134@qq.com
  717. * @date 2023/4/7
  718. */
  719. public function makeDatebase(string $tableName, string $tableComment, array $tableField = [])
  720. {
  721. $softDelete = false;
  722. $timestamps = false;
  723. $indexField = [];
  724. //创建表
  725. $table = new Table($tableName, ['comment' => $tableComment], $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'] === 'addTimestamps') {
  743. //创建修改和增加时间
  744. $table->addTimestamps();
  745. $timestamps = true;
  746. } else {
  747. $option['comment'] = $item['comment'];
  748. $fieldType = $this->changeTabelRule($item['field_type']);
  749. if (in_array($fieldType, ['text', 'longtext', 'tinytext'])) {
  750. unset($option['limit']);
  751. }
  752. $table->addColumn($item['field'], $this->changeTabelRule($item['field_type']), $option);
  753. }
  754. }
  755. //创建索引
  756. if (!empty($data['tableIndex'])) {
  757. $indexField = $data['tableIndex'];
  758. foreach ($data['tableIndex'] as $item) {
  759. $table->addIndex($item);
  760. }
  761. }
  762. return compact('indexField', 'softDelete', 'timestamps', 'table');
  763. }
  764. /**
  765. * 创建文件返回文件路径和内容
  766. * @param string $tableName
  767. * @param string $routeName
  768. * @param bool $isMake
  769. * @param array $options
  770. * @param array $filePath
  771. * @param string $basePath
  772. * @return array[]
  773. * @author 等风来
  774. * @email 136327134@qq.com
  775. * @date 2023/4/7
  776. */
  777. public function makeFile(string $tableName, string $routeName, bool $isMake = false, array $options = [], array $filePath = [], string $basePath = '')
  778. {
  779. $options['fromField'] = is_array($options['fromField']) ? $options['fromField'] : [];
  780. $options['columnField'] = is_array($options['columnField']) ? $options['columnField'] : [];
  781. //生成模型
  782. $model = app()->make(Model::class);
  783. $model->setFilePathName($filePath['model'] ?? '')->setbasePath($basePath)->handle($tableName, $options);
  784. //生成dao
  785. $dao = app()->make(Dao::class);
  786. $dao->setFilePathName($filePath['dao'] ?? '')->setbasePath($basePath)->handle($tableName, [
  787. 'usePath' => $model->getUsePath(),
  788. 'modelName' => $options['modelName'] ?? '',
  789. ]);
  790. //生成service
  791. $service = app()->make(Service::class);
  792. $service->setFilePathName($filePath['service'] ?? '')->setbasePath($basePath)->handle($tableName, [
  793. 'field' => $options['fromField'],
  794. 'key' => $options['key'],
  795. 'usePath' => $dao->getUsePath(),
  796. 'modelName' => $options['modelName'] ?? '',
  797. ]);
  798. //生成验证器
  799. $validate = app()->make(Validate::class);
  800. $validate->setFilePathName($filePath['validate'] ?? '')->setbasePath($basePath)->handle($tableName, [
  801. 'field' => $options['fromField'],
  802. 'modelName' => $options['modelName'] ?? '',
  803. ]);
  804. //生成控制器
  805. $controller = app()->make(Controller::class);
  806. $controller->setFilePathName($filePath['controller'] ?? '')->setbasePath($basePath)->handle($tableName, [
  807. 'usePath' => $service->getUsePath(),
  808. 'modelName' => $options['modelName'] ?? '',
  809. 'validateName' => '\\' . str_replace('/', '\\', $validate->getUsePath()) . 'Validate::class',
  810. 'field' => array_column($options['fromField'], 'field'),
  811. ]);
  812. //生成路由
  813. $route = app()->make(Route::class);
  814. $route->setFilePathName($filePath['route'] ?? '')->setbasePath($basePath)->handle($tableName, [
  815. 'menus' => $options['modelName'] ?? $options['menuName'],
  816. 'route' => $routeName
  817. ]);
  818. //生成前台路由
  819. $viewRouter = app()->make(ViewRouter::class);
  820. $viewRouter->setFilePathName($filePath['router'] ?? '')->setbasePath($basePath)->handle($tableName, [
  821. 'route' => $routeName,
  822. 'menuName' => $options['menuName'],
  823. ]);
  824. //生成前台接口
  825. $viewApi = app()->make(ViewApi::class);
  826. $viewApi->setFilePathName($filePath['api'] ?? '')->setbasePath($basePath)->handle($tableName, [
  827. 'route' => $routeName,
  828. ]);
  829. //生成前台页面
  830. $viewPages = app()->make(ViewPages::class);
  831. $viewPages->setFilePathName($filePath['pages'] ?? '')->setbasePath($basePath)->handle($tableName, [
  832. 'field' => $options['columnField'],
  833. 'route' => $routeName,
  834. 'key' => $options['key'],
  835. 'pathApiJs' => '@/' . str_replace('\\', '/', str_replace([Make::adminTemplatePath(), '.js'], '', $viewApi->getPath())),
  836. ]);
  837. //创建文件
  838. if ($isMake) {
  839. FileService::batchMakeFiles([$model, $validate, $dao, $service, $controller, $route, $viewApi, $viewPages, $viewRouter]);
  840. }
  841. return [
  842. 'controller' => [
  843. 'path' => $this->replace($controller->getPath()),
  844. 'content' => $controller->getContent()
  845. ],
  846. 'model' => [
  847. 'path' => $this->replace($model->getPath()),
  848. 'content' => $model->getContent()
  849. ],
  850. 'dao' => [
  851. 'path' => $this->replace($dao->getPath()),
  852. 'content' => $dao->getContent()
  853. ],
  854. 'route' => [
  855. 'path' => $this->replace($route->getPath()),
  856. 'content' => $route->getContent()
  857. ],
  858. 'service' => [
  859. 'path' => $this->replace($service->getPath()),
  860. 'content' => $service->getContent()
  861. ],
  862. 'validate' => [
  863. 'path' => $this->replace($validate->getPath()),
  864. 'content' => $validate->getContent()
  865. ],
  866. 'router' => [
  867. 'path' => $this->replace($viewRouter->getPath()),
  868. 'content' => $viewRouter->getContent()
  869. ],
  870. 'api' => [
  871. 'path' => $this->replace($viewApi->getPath()),
  872. 'content' => $viewApi->getContent()
  873. ],
  874. 'pages' => [
  875. 'path' => $this->replace($viewPages->getPath()),
  876. 'content' => $viewPages->getContent()
  877. ],
  878. ];
  879. }
  880. protected function replace(string $path)
  881. {
  882. return str_replace([app()->getRootPath(), Make::adminTemplatePath()], '', $path);
  883. }
  884. /**
  885. * @param string $tableName
  886. * @param bool $fullName
  887. * @return string
  888. * @author 等风来
  889. * @email 136327134@qq.com
  890. * @date 2023/4/7
  891. */
  892. public function getTableName(string $tableName, bool $fullName = true)
  893. {
  894. $tablePrefix = config('database.connections.mysql.prefix');
  895. $pattern = '/^' . $tablePrefix . '/i';
  896. return ($fullName ? $tablePrefix : '') . (preg_replace($pattern, '', $tableName));
  897. }
  898. }