SystemCrudServices.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  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' => 'radio',
  161. 'label' => '单选框',
  162. ],
  163. [
  164. 'value' => 'select',
  165. 'label' => '下拉框',
  166. ],
  167. [
  168. 'value' => 'frameImageOne',
  169. 'label' => '单图选择'
  170. ],
  171. [
  172. 'value' => 'frameImages',
  173. 'label' => '多图选择'
  174. ],
  175. ],
  176. 'rule' => $rule
  177. ];
  178. }
  179. /**
  180. * 改变数据库类型
  181. * @param string $type
  182. * @return string
  183. * @author 等风来
  184. * @email 136327134@qq.com
  185. * @date 2023/4/13
  186. */
  187. public function changeTabelRule(string $type)
  188. {
  189. if (!in_array($type, $this->getTabelRule()['types'])) {
  190. throw new AdminException(500047);
  191. }
  192. return $this->getTabelRule()['rule'][$type] ?? $type;
  193. }
  194. /**
  195. * @param string $tableName
  196. * @return mixed
  197. * @author 等风来
  198. * @email 136327134@qq.com
  199. * @date 2023/4/14
  200. */
  201. public function getTableInfo(string $tableName)
  202. {
  203. $sql = 'SELECT * FROM `information_schema`.`TABLES` WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?';
  204. $tableInfo = Db::query($sql, [config('database.connections.mysql.database'), $this->getTableName($tableName)]);
  205. return $tableInfo[0] ?? [];
  206. }
  207. /**
  208. * 获取表字段
  209. * @param string $tableName
  210. * @return mixed
  211. * @author 等风来
  212. * @email 136327134@qq.com
  213. * @date 2023/4/7
  214. */
  215. public function getColumnNamesList(string $tableName)
  216. {
  217. $sql = 'SELECT * FROM `information_schema`.`columns` WHERE TABLE_SCHEMA = ? AND table_name = ? ORDER BY ORDINAL_POSITION';
  218. $column = Db::query($sql, [config('database.connections.mysql.database'), $this->getTableName($tableName)]);
  219. $columns = [];
  220. foreach ($column as $item) {
  221. $column = [
  222. 'name' => $item['COLUMN_NAME'],
  223. 'type' => $item['DATA_TYPE'],
  224. 'dataType' => stripos($item['COLUMN_TYPE'], '(') !== false ? substr_replace($item['COLUMN_TYPE'], '', stripos($item['COLUMN_TYPE'], ')') + 1) : $item['COLUMN_TYPE'],
  225. 'default' => $item['COLUMN_DEFAULT'],
  226. 'null' => $item['IS_NULLABLE'] == 'YES',
  227. 'primaryKey' => $item['COLUMN_KEY'] == 'PRI',
  228. 'unsigned' => (bool)stripos($item['COLUMN_TYPE'], 'unsigned'),
  229. 'autoIncrement' => stripos($item['EXTRA'], 'auto_increment') !== false,
  230. 'comment' => $item['COLUMN_COMMENT'],
  231. 'limit' => $item['CHARACTER_MAXIMUM_LENGTH'] ?: $item['NUMERIC_PRECISION'],
  232. ];
  233. $columns[$item['COLUMN_NAME']] = $column;
  234. }
  235. return $columns;
  236. }
  237. /**
  238. * @param array $data
  239. * @return array
  240. * @author 等风来
  241. * @email 136327134@qq.com
  242. * @date 2023/4/12
  243. */
  244. public function valueReplace(array $data)
  245. {
  246. $replace = ['phar://'];
  247. $newData = [];
  248. foreach ($data as $key => $item) {
  249. if (is_array($item)) {
  250. $item = $this->valueReplace($item);
  251. } else {
  252. $item = str_replace($replace, '', $item);
  253. }
  254. $newData[str_replace($replace, '', $key)] = $item;
  255. }
  256. return $newData;
  257. }
  258. /**
  259. * 更新表字段
  260. * @param string $tableName
  261. * @param string $field
  262. * @param string $changeFiled
  263. * @param string $type
  264. * @param string $limit
  265. * @param string $default
  266. * @param string $comment
  267. * @param array $options
  268. * @return mixed
  269. * @author 等风来
  270. * @email 136327134@qq.com
  271. * @date 2023/4/24
  272. */
  273. protected function updateAlter(string $tableName, string $field, string $changeFiled, string $type, $limit = '', string $default = '', string $comment = '', array $options = [])
  274. {
  275. $tableName = $this->getTableName($tableName);
  276. $comment = addslashes($comment);
  277. $field = addslashes($field);
  278. $changeFiled = addslashes($changeFiled);
  279. $type = addslashes($type);
  280. $default = addslashes($default);
  281. if (in_array(strtolower($type), ['text', 'longtext', 'tinytext'])) {
  282. $sql = "ALTER TABLE `$tableName` CHANGE `$field` `$changeFiled` $type CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '$comment';";
  283. } else {
  284. $sql = "ALTER TABLE `$tableName` CHANGE `$field` `$changeFiled` $type($limit) NOT NULL DEFAULT '$default' COMMENT '$comment';";
  285. }
  286. return Db::execute($sql);
  287. }
  288. /**
  289. * 添加字段
  290. * @param string $tableName
  291. * @param string $field
  292. * @param string $prevFiled
  293. * @param string $type
  294. * @param string $limit
  295. * @param string $default
  296. * @param string $comment
  297. * @param array $options
  298. * @return mixed
  299. * @author 等风来
  300. * @email 136327134@qq.com
  301. * @date 2023/4/24
  302. */
  303. public function addAlter(string $tableName, string $field, string $prevFiled, string $type, $limit = '', string $default = '', string $comment = '', array $options = [])
  304. {
  305. $tableName = $this->getTableName($tableName);
  306. $comment = addslashes($comment);
  307. $field = addslashes($field);
  308. $prevFiled = addslashes($prevFiled);
  309. $type = addslashes($type);
  310. $default = addslashes($default);
  311. if ($prevFiled) {
  312. $after = "AFTER `$prevFiled`";
  313. } else {
  314. $after = "";
  315. }
  316. if (in_array(strtolower($type), ['text', 'longtext', 'tinytext'])) {
  317. $sql = "ALTER TABLE `$tableName` ADD `$field` $type NULL COMMENT '$comment' $after;";
  318. } else {
  319. $sql = "ALTER TABLE `$tableName` ADD `$field` $type($limit) NOT NULL DEFAULT '$default' COMMENT '$comment' $after;";
  320. }
  321. return Db::execute($sql);
  322. }
  323. /**
  324. * 删除表字段
  325. * @param string $tableName
  326. * @param string $field
  327. * @return mixed
  328. * @author 等风来
  329. * @email 136327134@qq.com
  330. * @date 2023/4/24
  331. */
  332. protected function deleteAlter(string $tableName, string $field)
  333. {
  334. $tableName = $this->getTableName($tableName);
  335. $field = addslashes($field);
  336. $sql = "ALTER TABLE `$tableName` DROP `$field`";
  337. return Db::execute($sql);
  338. }
  339. /**
  340. * 对比字段变动了更改
  341. * @param string $tableName
  342. * @param array $deleteField
  343. * @param array $tableField
  344. * @author 等风来
  345. * @email 136327134@qq.com
  346. * @date 2023/4/24
  347. */
  348. protected function diffAlter(string $tableName, array $deleteField, array $tableField)
  349. {
  350. $updateAlter = [];
  351. $addAlter = [];
  352. $columns = $this->getColumnNamesList($tableName);
  353. $fieldAll = array_column($columns, 'name');
  354. $prevFiled = $columns[count($columns) - 1]['name'] ?? '';
  355. //对比数据库字段
  356. foreach ($tableField as $item) {
  357. if ($item['primaryKey']) {
  358. continue;
  359. }
  360. //前台新增的字段进行添加
  361. if (!(isset($item['default_field']) &&
  362. isset($item['default_field_type']) &&
  363. isset($item['default_limit']) &&
  364. isset($item['default_comment']) &&
  365. isset($item['default_default']))
  366. ) {
  367. if (!in_array($item['field'], $fieldAll)) {
  368. $addAlter[] = [
  369. 'prev_filed' => $prevFiled,
  370. 'field' => $item['field'],
  371. 'limit' => $item['limit'],
  372. 'type' => $item['field_type'],
  373. 'comment' => $item['comment'],
  374. 'default' => $item['default'],
  375. ];
  376. }
  377. continue;
  378. } else {
  379. //默认字段没有在数据库中,需要添加字段
  380. if (!in_array($item['default_field'], $fieldAll)) {
  381. $addAlter[] = [
  382. 'prev_filed' => $prevFiled,
  383. 'field' => $item['field'],
  384. 'limit' => $item['limit'],
  385. 'type' => $item['field_type'],
  386. 'comment' => $item['comment'],
  387. 'default' => $item['default'],
  388. ];
  389. continue;
  390. }
  391. }
  392. if ($item['default_field'] != $item['field'] && in_array($item['field_type'], ['addTimestamps', 'addSoftDelete'])) {
  393. throw new AdminException($item['field'] . '字段不允许被更改');
  394. }
  395. //数据库表存在的,字段,并且被修改
  396. if ($item['default_field'] != $item['field'] ||
  397. $item['default_field_type'] != $item['field_type'] ||
  398. $item['default_limit'] != $item['limit'] ||
  399. $item['default_comment'] != $item['comment'] ||
  400. $item['default_default'] != $item['default']) {
  401. $updateAlter[] = [
  402. 'default_field' => $item['default_field'],
  403. 'field' => $item['field'],
  404. 'limit' => $item['limit'],
  405. 'type' => $item['field_type'],
  406. 'comment' => $item['comment'],
  407. 'default' => $item['default'],
  408. ];
  409. }
  410. }
  411. //更新数据库字段
  412. foreach ($updateAlter as $item) {
  413. $this->updateAlter($tableName, $item['default_field'], $item['field'], $item['type'], $item['limit'], $item['default'], $item['comment']);
  414. }
  415. //添加字段
  416. foreach ($addAlter as $item) {
  417. $this->addAlter($tableName, $item['field'], $item['prev_filed'], $item['type'], $item['limit'], $item['default'], $item['comment']);
  418. }
  419. //删除多余字段
  420. foreach ($deleteField as $item) {
  421. $this->deleteAlter($tableName, $item);
  422. }
  423. }
  424. /**
  425. * 创建
  426. * @param array $data
  427. * @return mixed
  428. * @author 等风来
  429. * @email 136327134@qq.com
  430. * @date 2023/4/11
  431. */
  432. public function createCrud(int $id, array $data)
  433. {
  434. $tableName = $data['tableName'];
  435. $tableComment = $data['tableComment'] ?? $data['menuName'];
  436. $tableField = $this->valueReplace($data['tableField']);
  437. $filePath = $this->valueReplace($data['filePath']);
  438. $modelName = $data['modelName'] ?? $data['menuName'] ?? $tableName;
  439. //检测是否为系统表
  440. if (in_array($tableName, self::NOT_CRUD_TABANAME)) {
  441. throw new AdminException(500044);
  442. }
  443. $data['softDelete'] = false;
  444. $tableInfo = null;
  445. if ($id) {
  446. //删除数据库表
  447. $tableInfo = $this->getTableInfo($tableName);
  448. if ($tableInfo) {
  449. //对比字段进行更新/删除字段
  450. $this->diffAlter($tableName, $data['deleteField'], $tableField);
  451. }
  452. }
  453. //创建数据库
  454. if ($tableField && (!$data['isTable'] || !$tableInfo)) {
  455. $tableCreateInfo = $this->makeDatebase($tableName, $tableComment, $tableField);
  456. if ($tableCreateInfo['softDelete']) {
  457. $data['softDelete'] = true;
  458. }
  459. }
  460. //读取表结构
  461. $column = $this->getColumnNamesList($tableName);
  462. if (!$column) {
  463. throw new AdminException(500049, ['_name' => $tableName]);
  464. }
  465. //读取数据库字段信息
  466. $tableInfo = $this->getTableInfo($tableName);
  467. //获取主键
  468. foreach ($column as $value) {
  469. if ($value['primaryKey']) {
  470. $data['key'] = $value['name'];
  471. break;
  472. }
  473. }
  474. $routeName = 'crud/' . Str::snake($tableName);
  475. $uniqueAuth = Str::snake($tableName) . '-crud-list-index';
  476. //增加保存的绝对路径
  477. foreach ($filePath as $k => $i) {
  478. if (in_array($k, ['pages', 'router', 'api'])) {
  479. $filePath[$k] = Make::adminTemplatePath() . $i;
  480. } else {
  481. $filePath[$k] = app()->getRootPath() . $i;
  482. }
  483. }
  484. //创建菜单
  485. if (!$data['menuName']) {
  486. $data['menuName'] = $tableName;
  487. }
  488. $dataMenu = [
  489. 'pid' => $data['pid'],
  490. 'menu_name' => $data['menuName'],
  491. 'menu_path' => '/' . $routeName,
  492. 'auth_type' => 1,
  493. 'is_show' => 1,
  494. 'is_del' => 0,
  495. 'unique_auth' => $uniqueAuth,
  496. 'is_header' => $data['pid'] ? 0 : 1,
  497. ];
  498. $crudInfo = null;
  499. if ($id) {
  500. $crudInfo = $this->dao->get($id);
  501. }
  502. $res = $this->transaction(function () use ($crudInfo, $tableInfo, $modelName, $filePath, $tableName, $routeName, $data, $dataMenu) {
  503. $routeService = app()->make(SystemRouteServices::class);
  504. //修改菜单名称
  505. if ($crudInfo) {
  506. app()->make(SystemMenusServices::class)->update($crudInfo->menu_id, $dataMenu);
  507. //删除掉添加的路由权限
  508. if ($crudInfo->routes_id) {
  509. $routeService->deleteRoutes($crudInfo->routes_id);
  510. }
  511. //删除掉权限路由
  512. if ($crudInfo->menu_ids) {
  513. app()->make(SystemMenusServices::class)->deleteMenus($crudInfo->menu_ids);
  514. }
  515. $menuInfo = (object)['id' => $crudInfo->menu_id];
  516. } else {
  517. $menuInfo = app()->make(SystemMenusServices::class)->save($dataMenu);
  518. }
  519. //写入路由权限
  520. $cateId = app()->make(SystemRouteServices::class)->topCateId('adminapi', 'CRUD');
  521. $ruleData = [
  522. [
  523. 'path' => $routeName,
  524. 'method' => 'GET',
  525. 'name' => $modelName . '列表接口',
  526. 'app_name' => 'adminapi',
  527. 'cate_id' => $cateId,
  528. 'unique_auth' => '',
  529. 'add_time' => date('Y-m-d H:i:s')
  530. ],
  531. [
  532. 'path' => $routeName . '/create',
  533. 'method' => 'GET',
  534. 'name' => $modelName . '获取创建表单接口',
  535. 'app_name' => 'adminapi',
  536. 'cate_id' => $cateId,
  537. 'unique_auth' => Str::snake($tableName) . '-add',
  538. 'add_time' => date('Y-m-d H:i:s')
  539. ],
  540. [
  541. 'path' => $routeName,
  542. 'method' => 'POST',
  543. 'name' => $modelName . '保存接口',
  544. 'app_name' => 'adminapi',
  545. 'cate_id' => $cateId,
  546. 'unique_auth' => '',
  547. 'add_time' => date('Y-m-d H:i:s')
  548. ],
  549. [
  550. 'path' => $routeName . '/<id>/edit',
  551. 'method' => 'GET',
  552. 'name' => $modelName . '获取修改表单接口',
  553. 'app_name' => 'adminapi',
  554. 'cate_id' => $cateId,
  555. 'unique_auth' => '',
  556. 'add_time' => date('Y-m-d H:i:s')
  557. ],
  558. [
  559. 'path' => $routeName . '/<id>',
  560. 'method' => 'PUT',
  561. 'name' => $modelName . '修改接口',
  562. 'app_name' => 'adminapi',
  563. 'cate_id' => $cateId,
  564. 'unique_auth' => '',
  565. 'add_time' => date('Y-m-d H:i:s')
  566. ],
  567. [
  568. 'path' => $routeName . '/<id>',
  569. 'method' => 'DELETE',
  570. 'name' => $modelName . '删除接口',
  571. 'app_name' => 'adminapi',
  572. 'cate_id' => $cateId,
  573. 'unique_auth' => '',
  574. 'add_time' => date('Y-m-d H:i:s')
  575. ],
  576. ];
  577. $routeList = $routeService->saveAll($ruleData);
  578. $routeIds = array_column($routeList->toArray(), 'id');
  579. //记录权限加入菜单表
  580. $menuData = [];
  581. foreach ($ruleData as $item) {
  582. $menuData[] = [
  583. 'pid' => $menuInfo->id ?: 0,
  584. 'methods' => $item['method'],
  585. 'api_url' => $item['path'],
  586. 'unique_auth' => $item['unique_auth'],
  587. 'menu_name' => $item['name'],
  588. 'is_del' => 0,
  589. 'auth_type' => 2,
  590. ];
  591. }
  592. $menus = app()->make(SystemMenusServices::class)->saveAll($menuData);
  593. $menuIds = array_column($menus->toArray(), 'id');
  594. //生成文件
  595. $make = $this->makeFile($tableName, $routeName, true, $data, $filePath);
  596. $makePath = [];
  597. foreach ($make as $key => $item) {
  598. $makePath[$key] = $item['path'];
  599. }
  600. $crudDate = [
  601. 'pid' => $data['pid'],
  602. 'name' => $data['menuName'],
  603. 'model_name' => $data['modelName'],
  604. 'table_name' => $tableName,
  605. 'table_comment' => $tableInfo['TABLE_COMMENT'] ?? '',
  606. 'table_collation' => $tableInfo['TABLE_COLLATION'] ?? '',
  607. 'field' => json_encode($data),//提交的数据
  608. 'menu_ids' => json_encode($menuIds),//生成的菜单id
  609. 'make_path' => json_encode($makePath),
  610. 'routes_id' => json_encode($routeIds),
  611. ];
  612. if ($crudInfo) {
  613. $res = $this->dao->update($crudInfo->id, $crudDate);
  614. } else {
  615. $crudDate['add_time'] = time();
  616. //记录crud生成
  617. $res = $this->dao->save($crudDate);
  618. }
  619. return $res;
  620. });
  621. return $res->toArray();
  622. }
  623. /**
  624. * 获取数据库配置
  625. * @return array
  626. */
  627. protected function getDbConfig(): array
  628. {
  629. $default = app()->config->get('database.default');
  630. $config = app()->config->get("database.connections.{$default}");
  631. if (0 == $config['deploy']) {
  632. $dbConfig = [
  633. 'adapter' => $config['type'],
  634. 'host' => $config['hostname'],
  635. 'name' => $config['database'],
  636. 'user' => $config['username'],
  637. 'pass' => $config['password'],
  638. 'port' => $config['hostport'],
  639. 'charset' => $config['charset'],
  640. 'table_prefix' => $config['prefix'],
  641. ];
  642. } else {
  643. $dbConfig = [
  644. 'adapter' => explode(',', $config['type'])[0],
  645. 'host' => explode(',', $config['hostname'])[0],
  646. 'name' => explode(',', $config['database'])[0],
  647. 'user' => explode(',', $config['username'])[0],
  648. 'pass' => explode(',', $config['password'])[0],
  649. 'port' => explode(',', $config['hostport'])[0],
  650. 'charset' => explode(',', $config['charset'])[0],
  651. 'table_prefix' => explode(',', $config['prefix'])[0],
  652. ];
  653. }
  654. $table = app()->config->get('database.migration_table', 'migrations');
  655. $dbConfig['default_migration_table'] = $dbConfig['table_prefix'] . $table;
  656. return $dbConfig;
  657. }
  658. public function getAdapter()
  659. {
  660. $options = $this->getDbConfig();
  661. $adapter = AdapterFactory::instance()->getAdapter($options['adapter'], $options);
  662. if ($adapter->hasOption('table_prefix') || $adapter->hasOption('table_suffix')) {
  663. $adapter = AdapterFactory::instance()->getWrapper('prefix', $adapter);
  664. }
  665. return $adapter;
  666. }
  667. /**
  668. * 创建数据库
  669. * @param string $tableName
  670. * @param string $tableComment
  671. * @param array $tableField
  672. * @return array
  673. * @author 等风来
  674. * @email 136327134@qq.com
  675. * @date 2023/4/7
  676. */
  677. public function makeDatebase(string $tableName, string $tableComment, array $tableField = [])
  678. {
  679. $softDelete = false;
  680. $timestamps = false;
  681. $indexField = [];
  682. //创建表
  683. $table = new Table($tableName, ['comment' => $tableComment], $this->getAdapter());
  684. //创建字段
  685. foreach ($tableField as $item) {
  686. $option = [];
  687. if (isset($item['limit'])) {
  688. $option['limit'] = (int)$item['limit'];
  689. }
  690. if (isset($item['default'])) {
  691. $option['default'] = $item['default'];
  692. }
  693. //创建伪删除
  694. if ($item['field_type'] === 'addSoftDelete') {
  695. $table->addSoftDelete();
  696. $softDelete = true;
  697. } else if ($item['field_type'] === 'addTimestamps') {
  698. //创建修改和增加时间
  699. $table->addTimestamps();
  700. $timestamps = true;
  701. } else {
  702. $option['comment'] = $item['comment'];
  703. $fieldType = $this->changeTabelRule($item['field_type']);
  704. if (in_array($fieldType, ['text', 'longtext', 'tinytext'])) {
  705. unset($option['limit']);
  706. }
  707. $table->addColumn($item['field'], $this->changeTabelRule($item['field_type']), $option);
  708. }
  709. }
  710. //创建索引
  711. if (!empty($data['tableIndex'])) {
  712. $indexField = $data['tableIndex'];
  713. foreach ($data['tableIndex'] as $item) {
  714. $table->addIndex($item);
  715. }
  716. }
  717. //执行创建
  718. $table->create();
  719. return compact('indexField', 'softDelete', 'timestamps');
  720. }
  721. /**
  722. * 创建文件返回文件路径和内容
  723. * @param string $tableName
  724. * @param string $routeName
  725. * @param bool $isMake
  726. * @param array $options
  727. * @param array $filePath
  728. * @param string $basePath
  729. * @return array[]
  730. * @author 等风来
  731. * @email 136327134@qq.com
  732. * @date 2023/4/7
  733. */
  734. public function makeFile(string $tableName, string $routeName, bool $isMake = false, array $options = [], array $filePath = [], string $basePath = '')
  735. {
  736. $options['fromField'] = is_array($options['fromField']) ? $options['fromField'] : [];
  737. $options['columnField'] = is_array($options['columnField']) ? $options['columnField'] : [];
  738. //生成模型
  739. $model = app()->make(Model::class);
  740. $model->setFilePathName($filePath['model'] ?? '')->setbasePath($basePath)->handle($tableName, $options);
  741. //生成dao
  742. $dao = app()->make(Dao::class);
  743. $dao->setFilePathName($filePath['dao'] ?? '')->setbasePath($basePath)->handle($tableName, [
  744. 'usePath' => $model->getUsePath(),
  745. ]);
  746. //生成service
  747. $service = app()->make(Service::class);
  748. $service->setFilePathName($filePath['service'] ?? '')->setbasePath($basePath)->handle($tableName, [
  749. 'field' => $options['fromField'],
  750. 'key' => $options['key'],
  751. 'usePath' => $dao->getUsePath(),
  752. 'modelName' => $options['modelName'] ?? '',
  753. ]);
  754. //生成验证器
  755. $validate = app()->make(Validate::class);
  756. $validate->setFilePathName($filePath['validate'] ?? '')->setbasePath($basePath)->handle($tableName, [
  757. 'field' => $options['fromField'],
  758. ]);
  759. //生成控制器
  760. $controller = app()->make(Controller::class);
  761. $controller->setFilePathName($filePath['controller'] ?? '')->setbasePath($basePath)->handle($tableName, [
  762. 'usePath' => $service->getUsePath(),
  763. 'validateName' => '\\' . str_replace('/', '\\', $validate->getUsePath()) . 'Validate::class',
  764. 'field' => array_column($options['fromField'], 'field'),
  765. ]);
  766. //生成路由
  767. $route = app()->make(Route::class);
  768. $route->setFilePathName($filePath['route'] ?? '')->setbasePath($basePath)->handle($tableName, [
  769. 'menus' => $options['modelName'] ?? $options['menuName'],
  770. 'route' => $routeName
  771. ]);
  772. //生成前台路由
  773. $viewRouter = app()->make(ViewRouter::class);
  774. $viewRouter->setFilePathName($filePath['router'] ?? '')->setbasePath($basePath)->handle($tableName, [
  775. 'route' => $routeName,
  776. 'menuName' => $options['menuName'],
  777. ]);
  778. //生成前台接口
  779. $viewApi = app()->make(ViewApi::class);
  780. $viewApi->setFilePathName($filePath['api'] ?? '')->setbasePath($basePath)->handle($tableName, [
  781. 'route' => $routeName,
  782. ]);
  783. //生成前台页面
  784. $viewPages = app()->make(ViewPages::class);
  785. $viewPages->setFilePathName($filePath['pages'] ?? '')->setbasePath($basePath)->handle($tableName, [
  786. 'field' => $options['columnField'],
  787. 'route' => $routeName,
  788. 'key' => $options['key'],
  789. 'pathApiJs' => '@/' . str_replace('\\', '/', str_replace([Make::adminTemplatePath(), '.js'], '', $viewApi->getPath())),
  790. ]);
  791. //创建文件
  792. if ($isMake) {
  793. FileService::batchMakeFiles([$model, $validate, $dao, $service, $controller, $route, $viewApi, $viewPages, $viewRouter]);
  794. }
  795. return [
  796. 'controller' => [
  797. 'path' => $this->replace($controller->getPath()),
  798. 'content' => $controller->getContent()
  799. ],
  800. 'model' => [
  801. 'path' => $this->replace($model->getPath()),
  802. 'content' => $model->getContent()
  803. ],
  804. 'dao' => [
  805. 'path' => $this->replace($dao->getPath()),
  806. 'content' => $dao->getContent()
  807. ],
  808. 'route' => [
  809. 'path' => $this->replace($route->getPath()),
  810. 'content' => $route->getContent()
  811. ],
  812. 'service' => [
  813. 'path' => $this->replace($service->getPath()),
  814. 'content' => $service->getContent()
  815. ],
  816. 'validate' => [
  817. 'path' => $this->replace($validate->getPath()),
  818. 'content' => $validate->getContent()
  819. ],
  820. 'router' => [
  821. 'path' => $this->replace($viewRouter->getPath()),
  822. 'content' => $viewRouter->getContent()
  823. ],
  824. 'api' => [
  825. 'path' => $this->replace($viewApi->getPath()),
  826. 'content' => $viewApi->getContent()
  827. ],
  828. 'pages' => [
  829. 'path' => $this->replace($viewPages->getPath()),
  830. 'content' => $viewPages->getContent()
  831. ],
  832. ];
  833. }
  834. protected function replace(string $path)
  835. {
  836. return str_replace([app()->getRootPath(), Make::adminTemplatePath()], '', $path);
  837. }
  838. /**
  839. * @param string $tableName
  840. * @param bool $fullName
  841. * @return string
  842. * @author 等风来
  843. * @email 136327134@qq.com
  844. * @date 2023/4/7
  845. */
  846. public function getTableName(string $tableName, bool $fullName = true)
  847. {
  848. $tablePrefix = config('database.connections.mysql.prefix');
  849. $pattern = '/^' . $tablePrefix . '/i';
  850. return ($fullName ? $tablePrefix : '') . (preg_replace($pattern, '', $tableName));
  851. }
  852. }