SystemCrudServices.php 38 KB

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