SystemCrudServices.php 31 KB

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