SystemCrudServices.php 35 KB

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