SystemCrudServices.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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\services\crud\Controller;
  17. use crmeb\services\crud\Dao;
  18. use crmeb\services\crud\Make;
  19. use crmeb\services\crud\Model;
  20. use crmeb\services\crud\Route;
  21. use crmeb\services\crud\Service;
  22. use crmeb\services\crud\Validate;
  23. use crmeb\services\crud\ViewApi;
  24. use crmeb\services\crud\ViewPages;
  25. use crmeb\services\crud\ViewRouter;
  26. use Phinx\Db\Adapter\AdapterFactory;
  27. use think\exception\ValidateException;
  28. use think\facade\Db;
  29. use think\helper\Str;
  30. use think\migration\Migrator;
  31. use Phinx\Db\Adapter\MysqlAdapter;
  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',
  52. ];
  53. /**
  54. * SystemCrudServices constructor.
  55. * @param SystemCrudDao $dao
  56. */
  57. public function __construct(SystemCrudDao $dao)
  58. {
  59. $this->dao = $dao;
  60. }
  61. /**
  62. * @return array
  63. * @author 等风来
  64. * @email 136327134@qq.com
  65. * @date 2023/4/11
  66. */
  67. public function getList()
  68. {
  69. [$page, $limit] = $this->getPageValue();
  70. $list = $this->dao->selectList([], 'add_time,id,name,table_name,table_comment,table_comment', $page, $limit, 'id desc');
  71. $count = $this->dao->count();
  72. return compact('list', 'count');
  73. }
  74. /**
  75. * 数据库字段类型
  76. * @return \string[][]
  77. * @author 等风来
  78. * @email 136327134@qq.com
  79. * @date 2023/4/11
  80. */
  81. public function getTabelRule()
  82. {
  83. $rule = [
  84. 'varchar' => 'string',
  85. 'int' => 'integer',
  86. 'biginteger' => 'bigint',
  87. 'tinyint' => 'boolean',
  88. ];
  89. return [
  90. 'types' => [
  91. 'varchar',
  92. 'char',
  93. 'text',
  94. 'longtext',
  95. 'tinytext',
  96. 'enum',
  97. 'blob',
  98. 'binary',
  99. 'varbinary',
  100. 'datetime',
  101. 'timestamp',
  102. 'time',
  103. 'date',
  104. 'year',
  105. 'boolean',
  106. 'tinyint',
  107. 'int',
  108. 'decimal',
  109. 'float',
  110. 'json',
  111. 'addTimestamps',
  112. 'addSoftDelete',
  113. ],
  114. 'rule' => $rule
  115. ];
  116. }
  117. /**
  118. * 改变数据库类型
  119. * @param string $type
  120. * @return string
  121. * @author 等风来
  122. * @email 136327134@qq.com
  123. * @date 2023/4/13
  124. */
  125. public function changeTabelRule(string $type)
  126. {
  127. if (!in_array($type, $this->getTabelRule()['types'])) {
  128. throw new ValidateException('类型不在支持范围');
  129. }
  130. return $this->getTabelRule()['rule'][$type] ?? $type;
  131. }
  132. /**
  133. * @param string $tableName
  134. * @return mixed
  135. * @author 等风来
  136. * @email 136327134@qq.com
  137. * @date 2023/4/14
  138. */
  139. public function getTableInfo(string $tableName)
  140. {
  141. $sql = 'SELECT * FROM `information_schema`.`TABLES` WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?';
  142. $tableInfo = Db::query($sql, [config('database.connections.mysql.database'), $this->getTableName($tableName)]);
  143. return $tableInfo[0] ?? [];
  144. }
  145. /**
  146. * 获取表字段
  147. * @param string $tableName
  148. * @return mixed
  149. * @author 等风来
  150. * @email 136327134@qq.com
  151. * @date 2023/4/7
  152. */
  153. public function getColumnNamesList(string $tableName)
  154. {
  155. $sql = 'SELECT * FROM `information_schema`.`columns` WHERE TABLE_SCHEMA = ? AND table_name = ? ORDER BY ORDINAL_POSITION';
  156. $column = Db::query($sql, [config('database.connections.mysql.database'), $this->getTableName($tableName)]);
  157. $columns = [];
  158. foreach ($column as $item) {
  159. $column = [
  160. 'name' => $item['COLUMN_NAME'],
  161. 'type' => $item['DATA_TYPE'],
  162. 'dataType' => stripos($item['COLUMN_TYPE'], '(') !== false ? substr_replace($item['COLUMN_TYPE'], '', stripos($item['COLUMN_TYPE'], ')') + 1) : $item['COLUMN_TYPE'],
  163. 'default' => $item['COLUMN_DEFAULT'],
  164. 'null' => $item['IS_NULLABLE'] == 'YES',
  165. 'primaryKey' => $item['COLUMN_KEY'] == 'PRI',
  166. 'unsigned' => (bool)stripos($item['COLUMN_TYPE'], 'unsigned'),
  167. 'autoIncrement' => stripos($item['EXTRA'], 'auto_increment') !== false,
  168. 'comment' => $item['COLUMN_COMMENT'],
  169. 'limit' => $item['CHARACTER_MAXIMUM_LENGTH'] ?: $item['NUMERIC_PRECISION'],
  170. ];
  171. $columns[$item['COLUMN_NAME']] = $column;
  172. }
  173. return $columns;
  174. }
  175. /**
  176. * @param array $data
  177. * @return array
  178. * @author 等风来
  179. * @email 136327134@qq.com
  180. * @date 2023/4/12
  181. */
  182. public function valueReplace(array $data)
  183. {
  184. $replace = ['phar://'];
  185. $newData = [];
  186. foreach ($data as $key => $item) {
  187. if (is_array($item)) {
  188. $item = $this->valueReplace($item);
  189. } else {
  190. $item = str_replace($replace, '', $item);
  191. }
  192. $newData[str_replace($replace, '', $key)] = $item;
  193. }
  194. return $newData;
  195. }
  196. /**
  197. * 创建
  198. * @param array $data
  199. * @return mixed
  200. * @author 等风来
  201. * @email 136327134@qq.com
  202. * @date 2023/4/11
  203. */
  204. public function createCrud(array $data)
  205. {
  206. $tableName = $data['tableName'];
  207. $tableComment = $data['tableComment'] ?? $data['menuName'];
  208. $tableField = $this->valueReplace($data['tableField']);
  209. $filePath = $this->valueReplace($data['filePath']);
  210. if ($this->dao->value(['table_name' => $tableName])) {
  211. throw new ValidateException('此表已经生成请在列表中查看');
  212. }
  213. $data['softDelete'] = false;
  214. //创建数据库
  215. if ($tableField && !$data['isTable']) {
  216. $tableCreateInfo = $this->makeDatebase($tableName, $tableComment, $tableField);
  217. if ($tableCreateInfo['softDelete']) {
  218. $data['softDelete'] = true;
  219. }
  220. }
  221. if (in_array($tableName, self::NOT_CRUD_TABANAME)) {
  222. throw new ValidateException('不能生成系统自带数据表');
  223. }
  224. //读取表结构
  225. $column = $this->getColumnNamesList($tableName);
  226. if (!$column) {
  227. throw new ValidateException('请先创建' . $tableName . '表');
  228. }
  229. $tableInfo = $this->getTableInfo($tableName);
  230. //获取主键
  231. foreach ($column as $value) {
  232. if ($value['primaryKey']) {
  233. $data['key'] = $value['name'];
  234. break;
  235. }
  236. }
  237. $routeName = 'crud/' . Str::snake($tableName);
  238. $uniqueAuth = Str::snake($tableName) . '-crud-list-index';
  239. //增加保存的绝对路径
  240. foreach ($filePath as $k => $i) {
  241. if (in_array($k, ['pages', 'router', 'api'])) {
  242. $filePath[$k] = Make::adminTemplatePath() . $i;
  243. } else {
  244. $filePath[$k] = app()->getRootPath() . $i;
  245. }
  246. }
  247. //创建菜单
  248. if (!$data['menuName']) {
  249. $data['menuName'] = $tableName;
  250. }
  251. $dataMenu = [
  252. 'pid' => $data['pid'],
  253. 'menu_name' => $data['menuName'],
  254. 'menu_path' => '/' . $routeName . '/list',
  255. 'auth_type' => 1,
  256. 'is_show' => 1,
  257. 'is_del' => 0,
  258. 'unique_auth' => $uniqueAuth,
  259. 'is_header' => $data['pid'] ? 0 : 1,
  260. ];
  261. $res = $this->transaction(function () use ($tableInfo, $filePath, $tableName, $routeName, $data, $dataMenu) {
  262. $menuInfo = app()->make(SystemMenusServices::class)->save($dataMenu);
  263. //写入路由权限
  264. $cateId = app()->make(SystemRouteServices::class)->topCateId('adminapi');
  265. $ruleData = [
  266. [
  267. 'path' => $routeName,
  268. 'method' => 'GET',
  269. 'name' => $data['menuName'] . '列表接口',
  270. 'app_name' => 'adminapi',
  271. 'cate_id' => $cateId,
  272. 'unique_auth' => '',
  273. 'add_time' => date('Y-m-d H:i:s')
  274. ],
  275. [
  276. 'path' => $routeName . '/create',
  277. 'method' => 'GET',
  278. 'name' => $data['menuName'] . '获取创建表单接口',
  279. 'app_name' => 'adminapi',
  280. 'cate_id' => $cateId,
  281. 'unique_auth' => Str::snake($tableName) . '-add',
  282. 'add_time' => date('Y-m-d H:i:s')
  283. ],
  284. [
  285. 'path' => $routeName,
  286. 'method' => 'POST',
  287. 'name' => $data['menuName'] . '保存数据接口',
  288. 'app_name' => 'adminapi',
  289. 'cate_id' => $cateId,
  290. 'unique_auth' => '',
  291. 'add_time' => date('Y-m-d H:i:s')
  292. ],
  293. [
  294. 'path' => $routeName . '/<id>/edit',
  295. 'method' => 'GET',
  296. 'name' => $data['menuName'] . '获取修改表单接口',
  297. 'app_name' => 'adminapi',
  298. 'cate_id' => $cateId,
  299. 'unique_auth' => '',
  300. 'add_time' => date('Y-m-d H:i:s')
  301. ],
  302. [
  303. 'path' => $routeName . '/<id>',
  304. 'method' => 'PUT',
  305. 'name' => $data['menuName'] . '修改数据接口',
  306. 'app_name' => 'adminapi',
  307. 'cate_id' => $cateId,
  308. 'unique_auth' => '',
  309. 'add_time' => date('Y-m-d H:i:s')
  310. ],
  311. [
  312. 'path' => $routeName . '/<id>',
  313. 'method' => 'DELETE',
  314. 'name' => $data['menuName'] . '删除数据接口',
  315. 'app_name' => 'adminapi',
  316. 'cate_id' => $cateId,
  317. 'unique_auth' => '',
  318. 'add_time' => date('Y-m-d H:i:s')
  319. ],
  320. ];
  321. app()->make(SystemRouteServices::class)->saveAll($ruleData);
  322. //记录权限加入菜单表
  323. $menuData = [];
  324. foreach ($ruleData as $item) {
  325. $menuData[] = [
  326. 'pid' => $menuInfo->id,
  327. 'methods' => $item['method'],
  328. 'api_url' => $item['path'],
  329. 'unique_auth' => $item['unique_auth'],
  330. 'name' => $item['name'],
  331. 'is_del' => 0,
  332. ];
  333. }
  334. $menus = app()->make(SystemMenusServices::class)->saveAll($menuData);
  335. $menuIds = array_column($menus->toArray(), 'id');
  336. array_push($menuIds, $menuInfo->id);
  337. //生成文件
  338. $make = $this->makeFile($tableName, $routeName, true, $data, $filePath);
  339. $makePath = [];
  340. foreach ($make as $key => $item) {
  341. $makePath[$key] = $item['path'];
  342. }
  343. //记录crud生成
  344. $res = $this->dao->save([
  345. 'pid' => $data['pid'],
  346. 'name' => $data['menuName'],
  347. 'table_name' => $tableName,
  348. 'table_comment' => $tableInfo['TABLE_COMMENT'] ?? '',
  349. 'table_collation' => $tableInfo['TABLE_COLLATION'] ?? '',
  350. 'field' => json_encode($data),//提交的数据
  351. 'menu_ids' => json_encode($menuIds),//生成的菜单id
  352. 'make_path' => json_encode($makePath),
  353. 'add_time' => time()
  354. ]);
  355. return $res;
  356. });
  357. return $res->toArray();
  358. }
  359. /**
  360. * 获取数据库配置
  361. * @return array
  362. */
  363. protected function getDbConfig(): array
  364. {
  365. $default = app()->config->get('database.default');
  366. $config = app()->config->get("database.connections.{$default}");
  367. if (0 == $config['deploy']) {
  368. $dbConfig = [
  369. 'adapter' => $config['type'],
  370. 'host' => $config['hostname'],
  371. 'name' => $config['database'],
  372. 'user' => $config['username'],
  373. 'pass' => $config['password'],
  374. 'port' => $config['hostport'],
  375. 'charset' => $config['charset'],
  376. 'table_prefix' => $config['prefix'],
  377. ];
  378. } else {
  379. $dbConfig = [
  380. 'adapter' => explode(',', $config['type'])[0],
  381. 'host' => explode(',', $config['hostname'])[0],
  382. 'name' => explode(',', $config['database'])[0],
  383. 'user' => explode(',', $config['username'])[0],
  384. 'pass' => explode(',', $config['password'])[0],
  385. 'port' => explode(',', $config['hostport'])[0],
  386. 'charset' => explode(',', $config['charset'])[0],
  387. 'table_prefix' => explode(',', $config['prefix'])[0],
  388. ];
  389. }
  390. $table = app()->config->get('database.migration_table', 'migrations');
  391. $dbConfig['default_migration_table'] = $dbConfig['table_prefix'] . $table;
  392. return $dbConfig;
  393. }
  394. public function getAdapter()
  395. {
  396. $options = $this->getDbConfig();
  397. $adapter = AdapterFactory::instance()->getAdapter($options['adapter'], $options);
  398. if ($adapter->hasOption('table_prefix') || $adapter->hasOption('table_suffix')) {
  399. $adapter = AdapterFactory::instance()->getWrapper('prefix', $adapter);
  400. }
  401. return $adapter;
  402. }
  403. /**
  404. * 创建数据库
  405. * @param string $tableName
  406. * @param string $tableComment
  407. * @param array $tableField
  408. * @return array
  409. * @author 等风来
  410. * @email 136327134@qq.com
  411. * @date 2023/4/7
  412. */
  413. public function makeDatebase(string $tableName, string $tableComment, array $tableField = [])
  414. {
  415. $softDelete = false;
  416. $timestamps = false;
  417. $indexField = [];
  418. //创建表
  419. $table = new Table($tableName, ['comment' => $tableComment], $this->getAdapter());
  420. //创建字段
  421. foreach ($tableField as $item) {
  422. $option = [];
  423. if (isset($item['limit'])) {
  424. $option['limit'] = (int)$item['limit'];
  425. }
  426. if (isset($item['default'])) {
  427. $option['default'] = $item['default'];
  428. }
  429. //创建伪删除
  430. if ($item['file_type'] === 'addSoftDelete') {
  431. $table->addSoftDelete();
  432. $softDelete = true;
  433. } else if ($item['file_type'] === 'addTimestamps') {
  434. //创建修改和增加时间
  435. $table->addTimestamps();
  436. $timestamps = true;
  437. } else {
  438. $option['comment'] = $item['comment'];
  439. $table->addColumn($item['field'], $this->changeTabelRule($item['file_type']), $option);
  440. }
  441. }
  442. //创建索引
  443. if (!empty($data['tableIndex'])) {
  444. $indexField = $data['tableIndex'];
  445. foreach ($data['tableIndex'] as $item) {
  446. $table->addIndex($item);
  447. }
  448. }
  449. //执行创建
  450. $table->create();
  451. return compact('indexField', 'softDelete', 'timestamps');
  452. }
  453. /**
  454. * 创建文件返回文件路径和内容
  455. * @param string $tableName
  456. * @param string $routeName
  457. * @param bool $isMake
  458. * @param array $options
  459. * @param array $filePath
  460. * @return array[]
  461. * @author 等风来
  462. * @email 136327134@qq.com
  463. * @date 2023/4/7
  464. */
  465. public function makeFile(string $tableName, string $routeName, bool $isMake = false, array $options = [], array $filePath = [])
  466. {
  467. $options['fromField'] = is_array($options['fromField']) ? $options['fromField'] : [];
  468. $options['columnField'] = is_array($options['columnField']) ? $options['columnField'] : [];
  469. //生成模型
  470. $model = app()->make(Model::class);
  471. [$modelContent, $modelPath, $usePath] = $model->setFilePathName($filePath['model'] ?? '')->isMake($isMake)->handle($tableName, $options);
  472. //生成dao
  473. $dao = app()->make(Dao::class);
  474. [$daoContent, $daoPath, $usePath] = $dao->setFilePathName($filePath['dao'] ?? '')->isMake($isMake)->handle($tableName, [
  475. 'usePath' => $usePath,
  476. ]);
  477. //生成service
  478. $service = app()->make(Service::class);
  479. [$serviceContent, $servicePath, $usePath] = $service->setFilePathName($filePath['service'] ?? '')->isMake($isMake)->handle($tableName, [
  480. 'field' => $options['fromField'],
  481. 'usePath' => $usePath,
  482. ]);
  483. //生成验证器
  484. $validate = app()->make(Validate::class);
  485. [$validateContent, $validatePath] = $validate->setFilePathName($filePath['validate'] ?? '')->isMake($isMake)->handle($tableName);
  486. //生成控制器
  487. $controller = app()->make(Controller::class);
  488. [$controllerContent, $controllerPath] = $controller->setFilePathName($filePath['controller'] ?? '')->isMake($isMake)->handle($tableName, [
  489. 'usePath' => $usePath,
  490. 'field' => array_column($options['fromField'], 'field'),
  491. ]);
  492. //生成路由
  493. $route = app()->make(Route::class);
  494. [$routeContent, $routePath] = $route->setFilePathName($filePath['route'] ?? '')->isMake($isMake)->handle($tableName, [
  495. 'menus' => $options['menuName'],
  496. 'route' => $routeName
  497. ]);
  498. //生成前台路由
  499. $viewRouter = app()->make(ViewRouter::class);
  500. [$routerContent, $routerPath] = $viewRouter->setFilePathName($filePath['router'] ?? '')->isMake($isMake)->handle($tableName, [
  501. 'route' => $routeName,
  502. 'menuName' => $options['menuName'],
  503. ]);
  504. //生成前台接口
  505. $viewApi = app()->make(ViewApi::class);
  506. [$apiContent, $apiPath] = $viewApi->setFilePathName($filePath['api'] ?? '')->isMake($isMake)->handle($tableName, [
  507. 'route' => $routeName,
  508. ]);
  509. //生成前台页面
  510. $viewPages = app()->make(ViewPages::class);
  511. [$pagesContent, $pagesPath] = $viewPages->setFilePathName($filePath['pages'] ?? '')->isMake($isMake)->handle($tableName, [
  512. 'field' => $options['columnField'],
  513. 'route' => $routeName,
  514. 'pathApiJs' => '@/' . str_replace('\\', '/', str_replace([Make::adminTemplatePath(), '.js'], '', $apiPath)),
  515. ]);
  516. return [
  517. 'controller' => [
  518. 'path' => $this->replace($controllerPath),
  519. 'content' => $controllerContent
  520. ],
  521. 'model' => [
  522. 'path' => $this->replace($modelPath),
  523. 'content' => $modelContent
  524. ],
  525. 'dao' => [
  526. 'path' => $this->replace($daoPath),
  527. 'content' => $daoContent
  528. ],
  529. 'route' => [
  530. 'path' => $this->replace($routePath),
  531. 'content' => $routeContent
  532. ],
  533. 'service' => [
  534. 'path' => $this->replace($servicePath),
  535. 'content' => $serviceContent
  536. ],
  537. 'validate' => [
  538. 'path' => $this->replace($validatePath),
  539. 'content' => $validateContent
  540. ],
  541. 'router' => [
  542. 'path' => $this->replace($routerPath),
  543. 'content' => $routerContent
  544. ],
  545. 'api' => [
  546. 'path' => $this->replace($apiPath),
  547. 'content' => $apiContent
  548. ],
  549. 'pages' => [
  550. 'path' => $this->replace($pagesPath),
  551. 'content' => $pagesContent
  552. ],
  553. ];
  554. }
  555. protected function replace(string $path)
  556. {
  557. return str_replace([app()->getRootPath(), Make::adminTemplatePath()], '', $path);
  558. }
  559. /**
  560. * @param string $tableName
  561. * @param bool $fullName
  562. * @return string
  563. * @author 等风来
  564. * @email 136327134@qq.com
  565. * @date 2023/4/7
  566. */
  567. public function getTableName(string $tableName, bool $fullName = true)
  568. {
  569. $tablePrefix = config('database.connections.mysql.prefix');
  570. $pattern = '/^' . $tablePrefix . '/i';
  571. return ($fullName ? $tablePrefix : '') . (preg_replace($pattern, '', $tableName));
  572. }
  573. }