SystemCrudServices.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  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. $tableInfo = null;
  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. if ($tableField && (!$data['isTable'] || !$tableInfo)) {
  483. $tableCreateInfo = $this->makeDatebase($tableName, $tableComment, $tableField);
  484. if ($tableCreateInfo['softDelete']) {
  485. $data['softDelete'] = true;
  486. }
  487. }
  488. //读取表结构
  489. $column = $this->getColumnNamesList($tableName);
  490. if (!$column) {
  491. throw new AdminException(500049, ['_name' => $tableName]);
  492. }
  493. //读取数据库字段信息
  494. $tableInfo = $this->getTableInfo($tableName);
  495. //获取主键
  496. foreach ($column as $value) {
  497. if ($value['primaryKey']) {
  498. $data['key'] = $value['name'];
  499. break;
  500. }
  501. }
  502. $routeName = 'crud/' . Str::snake($tableName);
  503. $uniqueAuth = Str::snake($tableName) . '-crud-list-index';
  504. //增加保存的绝对路径
  505. foreach ($filePath as $k => $i) {
  506. if (in_array($k, ['pages', 'router', 'api'])) {
  507. $filePath[$k] = Make::adminTemplatePath() . $i;
  508. } else {
  509. $filePath[$k] = app()->getRootPath() . $i;
  510. }
  511. }
  512. //创建菜单
  513. if (!$data['menuName']) {
  514. $data['menuName'] = $tableName;
  515. }
  516. $dataMenu = [
  517. 'pid' => $data['pid'],
  518. 'menu_name' => $data['menuName'],
  519. 'menu_path' => '/' . $routeName,
  520. 'auth_type' => 1,
  521. 'is_show' => 1,
  522. 'is_del' => 0,
  523. 'unique_auth' => $uniqueAuth,
  524. 'is_header' => $data['pid'] ? 0 : 1,
  525. ];
  526. $crudInfo = null;
  527. if ($id) {
  528. $crudInfo = $this->dao->get($id);
  529. }
  530. $res = $this->transaction(function () use ($crudInfo, $tableInfo, $modelName, $filePath, $tableName, $routeName, $data, $dataMenu) {
  531. $routeService = app()->make(SystemRouteServices::class);
  532. $meunService = app()->make(SystemMenusServices::class);
  533. //修改菜单名称
  534. if ($crudInfo) {
  535. //菜单存在的时候进行修改
  536. if ($crudInfo->menu_id && $meunService->value(['id' => [$crudInfo->menu_id]], 'id')) {
  537. $meunService->update($crudInfo->menu_id, $dataMenu);
  538. $menuInfo = (object)['id' => $crudInfo->menu_id];
  539. } else {
  540. $menuInfo = $meunService->save($dataMenu);
  541. }
  542. //删除掉添加的路由权限
  543. if ($crudInfo->route_ids) {
  544. $routeService->deleteRoutes($crudInfo->route_ids);
  545. }
  546. //删除掉权限路由
  547. if ($crudInfo->menu_ids) {
  548. app()->make(SystemMenusServices::class)->deleteMenus($crudInfo->menu_ids);
  549. }
  550. } else {
  551. $menuInfo = $meunService->save($dataMenu);
  552. }
  553. //写入路由权限
  554. $cateId = app()->make(SystemRouteServices::class)->topCateId('adminapi', 'CRUD');
  555. $ruleData = [
  556. [
  557. 'path' => $routeName,
  558. 'method' => 'GET',
  559. 'name' => $modelName . '列表接口',
  560. 'app_name' => 'adminapi',
  561. 'cate_id' => $cateId,
  562. 'unique_auth' => '',
  563. 'add_time' => date('Y-m-d H:i:s')
  564. ],
  565. [
  566. 'path' => $routeName . '/create',
  567. 'method' => 'GET',
  568. 'name' => $modelName . '获取创建表单接口',
  569. 'app_name' => 'adminapi',
  570. 'cate_id' => $cateId,
  571. 'unique_auth' => Str::snake($tableName) . '-add',
  572. 'add_time' => date('Y-m-d H:i:s')
  573. ],
  574. [
  575. 'path' => $routeName,
  576. 'method' => 'POST',
  577. 'name' => $modelName . '保存接口',
  578. 'app_name' => 'adminapi',
  579. 'cate_id' => $cateId,
  580. 'unique_auth' => '',
  581. 'add_time' => date('Y-m-d H:i:s')
  582. ],
  583. [
  584. 'path' => $routeName . '/<id>/edit',
  585. 'method' => 'GET',
  586. 'name' => $modelName . '获取修改表单接口',
  587. 'app_name' => 'adminapi',
  588. 'cate_id' => $cateId,
  589. 'unique_auth' => '',
  590. 'add_time' => date('Y-m-d H:i:s')
  591. ],
  592. [
  593. 'path' => $routeName . '/<id>',
  594. 'method' => 'PUT',
  595. 'name' => $modelName . '修改接口',
  596. 'app_name' => 'adminapi',
  597. 'cate_id' => $cateId,
  598. 'unique_auth' => '',
  599. 'add_time' => date('Y-m-d H:i:s')
  600. ],
  601. [
  602. 'path' => $routeName . '/<id>',
  603. 'method' => 'DELETE',
  604. 'name' => $modelName . '删除接口',
  605. 'app_name' => 'adminapi',
  606. 'cate_id' => $cateId,
  607. 'unique_auth' => '',
  608. 'add_time' => date('Y-m-d H:i:s')
  609. ],
  610. ];
  611. $routeList = $routeService->saveAll($ruleData);
  612. $routeIds = array_column($routeList->toArray(), 'id');
  613. //记录权限加入菜单表
  614. $menuData = [];
  615. foreach ($ruleData as $item) {
  616. $menuData[] = [
  617. 'pid' => $menuInfo->id ?: 0,
  618. 'methods' => $item['method'],
  619. 'api_url' => $item['path'],
  620. 'unique_auth' => $item['unique_auth'],
  621. 'menu_name' => $item['name'],
  622. 'is_del' => 0,
  623. 'auth_type' => 2,
  624. ];
  625. }
  626. $menus = app()->make(SystemMenusServices::class)->saveAll($menuData);
  627. $menuIds = array_column($menus->toArray(), 'id');
  628. //生成文件
  629. $make = $this->makeFile($tableName, $routeName, true, $data, $filePath);
  630. $makePath = [];
  631. foreach ($make as $key => $item) {
  632. $makePath[$key] = $item['path'];
  633. }
  634. $crudDate = [
  635. 'pid' => $data['pid'],
  636. 'name' => $data['menuName'],
  637. 'model_name' => $data['modelName'],
  638. 'table_name' => $tableName,
  639. 'table_comment' => $tableInfo['TABLE_COMMENT'] ?? '',
  640. 'table_collation' => $tableInfo['TABLE_COLLATION'] ?? '',
  641. 'field' => json_encode($data),//提交的数据
  642. 'menu_ids' => json_encode($menuIds),//生成的菜单id
  643. 'menu_id' => $menuInfo->id,//生成的菜单id
  644. 'make_path' => json_encode($makePath),
  645. 'route_ids' => json_encode($routeIds),
  646. ];
  647. if ($crudInfo) {
  648. $res = $this->dao->update($crudInfo->id, $crudDate);
  649. } else {
  650. $crudDate['add_time'] = time();
  651. //记录crud生成
  652. $res = $this->dao->save($crudDate);
  653. }
  654. return $res;
  655. });
  656. return $res->toArray();
  657. }
  658. /**
  659. * 获取数据库配置
  660. * @return array
  661. */
  662. protected function getDbConfig(): array
  663. {
  664. $default = app()->config->get('database.default');
  665. $config = app()->config->get("database.connections.{$default}");
  666. if (0 == $config['deploy']) {
  667. $dbConfig = [
  668. 'adapter' => $config['type'],
  669. 'host' => $config['hostname'],
  670. 'name' => $config['database'],
  671. 'user' => $config['username'],
  672. 'pass' => $config['password'],
  673. 'port' => $config['hostport'],
  674. 'charset' => $config['charset'],
  675. 'table_prefix' => $config['prefix'],
  676. ];
  677. } else {
  678. $dbConfig = [
  679. 'adapter' => explode(',', $config['type'])[0],
  680. 'host' => explode(',', $config['hostname'])[0],
  681. 'name' => explode(',', $config['database'])[0],
  682. 'user' => explode(',', $config['username'])[0],
  683. 'pass' => explode(',', $config['password'])[0],
  684. 'port' => explode(',', $config['hostport'])[0],
  685. 'charset' => explode(',', $config['charset'])[0],
  686. 'table_prefix' => explode(',', $config['prefix'])[0],
  687. ];
  688. }
  689. $table = app()->config->get('database.migration_table', 'migrations');
  690. $dbConfig['default_migration_table'] = $dbConfig['table_prefix'] . $table;
  691. return $dbConfig;
  692. }
  693. public function getAdapter()
  694. {
  695. $options = $this->getDbConfig();
  696. $adapter = AdapterFactory::instance()->getAdapter($options['adapter'], $options);
  697. if ($adapter->hasOption('table_prefix') || $adapter->hasOption('table_suffix')) {
  698. $adapter = AdapterFactory::instance()->getWrapper('prefix', $adapter);
  699. }
  700. return $adapter;
  701. }
  702. /**
  703. * 创建数据库
  704. * @param string $tableName
  705. * @param string $tableComment
  706. * @param array $tableField
  707. * @return array
  708. * @author 等风来
  709. * @email 136327134@qq.com
  710. * @date 2023/4/7
  711. */
  712. public function makeDatebase(string $tableName, string $tableComment, array $tableField = [])
  713. {
  714. $softDelete = false;
  715. $timestamps = false;
  716. $indexField = [];
  717. //创建表
  718. $table = new Table($tableName, ['comment' => $tableComment], $this->getAdapter());
  719. //创建字段
  720. foreach ($tableField as $item) {
  721. if (isset($item['primaryKey']) && $item['primaryKey']) {
  722. continue;
  723. }
  724. $option = [];
  725. if (isset($item['limit'])) {
  726. $option['limit'] = (int)$item['limit'];
  727. }
  728. if (isset($item['default'])) {
  729. $option['default'] = $item['default'];
  730. }
  731. //创建伪删除
  732. if ($item['field_type'] === 'addSoftDelete') {
  733. $table->addSoftDelete();
  734. $softDelete = true;
  735. } else if ($item['field_type'] === 'addTimestamps') {
  736. //创建修改和增加时间
  737. $table->addTimestamps();
  738. $timestamps = true;
  739. } else {
  740. $option['comment'] = $item['comment'];
  741. $fieldType = $this->changeTabelRule($item['field_type']);
  742. if (in_array($fieldType, ['text', 'longtext', 'tinytext'])) {
  743. unset($option['limit']);
  744. }
  745. $table->addColumn($item['field'], $this->changeTabelRule($item['field_type']), $option);
  746. }
  747. }
  748. //创建索引
  749. if (!empty($data['tableIndex'])) {
  750. $indexField = $data['tableIndex'];
  751. foreach ($data['tableIndex'] as $item) {
  752. $table->addIndex($item);
  753. }
  754. }
  755. //执行创建
  756. $table->create();
  757. return compact('indexField', 'softDelete', 'timestamps');
  758. }
  759. /**
  760. * 创建文件返回文件路径和内容
  761. * @param string $tableName
  762. * @param string $routeName
  763. * @param bool $isMake
  764. * @param array $options
  765. * @param array $filePath
  766. * @param string $basePath
  767. * @return array[]
  768. * @author 等风来
  769. * @email 136327134@qq.com
  770. * @date 2023/4/7
  771. */
  772. public function makeFile(string $tableName, string $routeName, bool $isMake = false, array $options = [], array $filePath = [], string $basePath = '')
  773. {
  774. $options['fromField'] = is_array($options['fromField']) ? $options['fromField'] : [];
  775. $options['columnField'] = is_array($options['columnField']) ? $options['columnField'] : [];
  776. //生成模型
  777. $model = app()->make(Model::class);
  778. $model->setFilePathName($filePath['model'] ?? '')->setbasePath($basePath)->handle($tableName, $options);
  779. //生成dao
  780. $dao = app()->make(Dao::class);
  781. $dao->setFilePathName($filePath['dao'] ?? '')->setbasePath($basePath)->handle($tableName, [
  782. 'usePath' => $model->getUsePath(),
  783. 'modelName' => $options['modelName'] ?? '',
  784. ]);
  785. //生成service
  786. $service = app()->make(Service::class);
  787. $service->setFilePathName($filePath['service'] ?? '')->setbasePath($basePath)->handle($tableName, [
  788. 'field' => $options['fromField'],
  789. 'key' => $options['key'],
  790. 'usePath' => $dao->getUsePath(),
  791. 'modelName' => $options['modelName'] ?? '',
  792. ]);
  793. //生成验证器
  794. $validate = app()->make(Validate::class);
  795. $validate->setFilePathName($filePath['validate'] ?? '')->setbasePath($basePath)->handle($tableName, [
  796. 'field' => $options['fromField'],
  797. 'modelName' => $options['modelName'] ?? '',
  798. ]);
  799. //生成控制器
  800. $controller = app()->make(Controller::class);
  801. $controller->setFilePathName($filePath['controller'] ?? '')->setbasePath($basePath)->handle($tableName, [
  802. 'usePath' => $service->getUsePath(),
  803. 'modelName' => $options['modelName'] ?? '',
  804. 'validateName' => '\\' . str_replace('/', '\\', $validate->getUsePath()) . 'Validate::class',
  805. 'field' => array_column($options['fromField'], 'field'),
  806. ]);
  807. //生成路由
  808. $route = app()->make(Route::class);
  809. $route->setFilePathName($filePath['route'] ?? '')->setbasePath($basePath)->handle($tableName, [
  810. 'menus' => $options['modelName'] ?? $options['menuName'],
  811. 'route' => $routeName
  812. ]);
  813. //生成前台路由
  814. $viewRouter = app()->make(ViewRouter::class);
  815. $viewRouter->setFilePathName($filePath['router'] ?? '')->setbasePath($basePath)->handle($tableName, [
  816. 'route' => $routeName,
  817. 'menuName' => $options['menuName'],
  818. ]);
  819. //生成前台接口
  820. $viewApi = app()->make(ViewApi::class);
  821. $viewApi->setFilePathName($filePath['api'] ?? '')->setbasePath($basePath)->handle($tableName, [
  822. 'route' => $routeName,
  823. ]);
  824. //生成前台页面
  825. $viewPages = app()->make(ViewPages::class);
  826. $viewPages->setFilePathName($filePath['pages'] ?? '')->setbasePath($basePath)->handle($tableName, [
  827. 'field' => $options['columnField'],
  828. 'route' => $routeName,
  829. 'key' => $options['key'],
  830. 'pathApiJs' => '@/' . str_replace('\\', '/', str_replace([Make::adminTemplatePath(), '.js'], '', $viewApi->getPath())),
  831. ]);
  832. //创建文件
  833. if ($isMake) {
  834. FileService::batchMakeFiles([$model, $validate, $dao, $service, $controller, $route, $viewApi, $viewPages, $viewRouter]);
  835. }
  836. return [
  837. 'controller' => [
  838. 'path' => $this->replace($controller->getPath()),
  839. 'content' => $controller->getContent()
  840. ],
  841. 'model' => [
  842. 'path' => $this->replace($model->getPath()),
  843. 'content' => $model->getContent()
  844. ],
  845. 'dao' => [
  846. 'path' => $this->replace($dao->getPath()),
  847. 'content' => $dao->getContent()
  848. ],
  849. 'route' => [
  850. 'path' => $this->replace($route->getPath()),
  851. 'content' => $route->getContent()
  852. ],
  853. 'service' => [
  854. 'path' => $this->replace($service->getPath()),
  855. 'content' => $service->getContent()
  856. ],
  857. 'validate' => [
  858. 'path' => $this->replace($validate->getPath()),
  859. 'content' => $validate->getContent()
  860. ],
  861. 'router' => [
  862. 'path' => $this->replace($viewRouter->getPath()),
  863. 'content' => $viewRouter->getContent()
  864. ],
  865. 'api' => [
  866. 'path' => $this->replace($viewApi->getPath()),
  867. 'content' => $viewApi->getContent()
  868. ],
  869. 'pages' => [
  870. 'path' => $this->replace($viewPages->getPath()),
  871. 'content' => $viewPages->getContent()
  872. ],
  873. ];
  874. }
  875. protected function replace(string $path)
  876. {
  877. return str_replace([app()->getRootPath(), Make::adminTemplatePath()], '', $path);
  878. }
  879. /**
  880. * @param string $tableName
  881. * @param bool $fullName
  882. * @return string
  883. * @author 等风来
  884. * @email 136327134@qq.com
  885. * @date 2023/4/7
  886. */
  887. public function getTableName(string $tableName, bool $fullName = true)
  888. {
  889. $tablePrefix = config('database.connections.mysql.prefix');
  890. $pattern = '/^' . $tablePrefix . '/i';
  891. return ($fullName ? $tablePrefix : '') . (preg_replace($pattern, '', $tableName));
  892. }
  893. }