SystemCrudServices.php 36 KB

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