SystemCrudServices.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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;
  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. $data['softDelete'] = false;
  211. //创建数据库
  212. if ($tableField && !$data['isTable']) {
  213. $tableCreateInfo = $this->makeDatebase($tableName, $tableComment, $tableField);
  214. if ($tableCreateInfo['softDelete']) {
  215. $data['softDelete'] = true;
  216. }
  217. }
  218. if (in_array($tableName, self::NOT_CRUD_TABANAME)) {
  219. throw new ValidateException('不能生成系统自带数据表');
  220. }
  221. //读取表结构
  222. $column = $this->getColumnNamesList($tableName);
  223. if (!$column) {
  224. throw new ValidateException('请先创建' . $tableName . '表');
  225. }
  226. $tableInfo = $this->getTableInfo($tableName);
  227. //获取主键
  228. foreach ($column as $value) {
  229. if ($value['primaryKey']) {
  230. $data['key'] = $value['name'];
  231. break;
  232. }
  233. }
  234. $routeName = 'crud/' . Str::snake($tableName);
  235. $uniqueAuth = Str::snake($tableName) . '-crud-list-index';
  236. //增加保存的绝对路径
  237. foreach ($filePath as $k => $i) {
  238. if (in_array($k, ['pages', 'router', 'api'])) {
  239. $filePath[$k] = Make::adminTemplatePath() . $i;
  240. } else {
  241. $filePath[$k] = app()->getRootPath() . $i;
  242. }
  243. }
  244. //创建菜单
  245. if (!$data['menuName']) {
  246. $data['menuName'] = $tableName;
  247. }
  248. $dataMenu = [
  249. 'pid' => $data['pid'],
  250. 'menu_name' => $data['menuName'],
  251. 'menu_path' => '/' . $routeName . '/list',
  252. 'auth_type' => 1,
  253. 'is_show' => 1,
  254. 'is_del' => 0,
  255. 'unique_auth' => $uniqueAuth,
  256. 'is_header' => $data['pid'] ? 0 : 1,
  257. ];
  258. $res = $this->transaction(function () use ($tableInfo, $filePath, $tableName, $routeName, $data, $dataMenu) {
  259. $menuInfo = app()->make(SystemMenusServices::class)->save($dataMenu);
  260. //写入路由权限
  261. $cateId = app()->make(SystemRouteServices::class)->topCateId('adminapi');
  262. $ruleData = [
  263. [
  264. 'path' => $routeName,
  265. 'method' => 'GET',
  266. 'name' => $data['menuName'] . '列表接口',
  267. 'app_name' => 'adminapi',
  268. 'cate_id' => $cateId,
  269. 'add_time' => date('Y-m-d H:i:s')
  270. ],
  271. [
  272. 'path' => $routeName . '/create',
  273. 'method' => 'GET',
  274. 'name' => $data['menuName'] . '获取创建表单接口',
  275. 'app_name' => 'adminapi',
  276. 'cate_id' => $cateId,
  277. 'add_time' => date('Y-m-d H:i:s')
  278. ],
  279. [
  280. 'path' => $routeName,
  281. 'method' => 'POST',
  282. 'name' => $data['menuName'] . '保存数据接口',
  283. 'app_name' => 'adminapi',
  284. 'cate_id' => $cateId,
  285. 'add_time' => date('Y-m-d H:i:s')
  286. ],
  287. [
  288. 'path' => $routeName . '/<id>/edit',
  289. 'method' => 'GET',
  290. 'name' => $data['menuName'] . '获取修改表单接口',
  291. 'app_name' => 'adminapi',
  292. 'cate_id' => $cateId,
  293. 'add_time' => date('Y-m-d H:i:s')
  294. ],
  295. [
  296. 'path' => $routeName . '/<id>',
  297. 'method' => 'PUT',
  298. 'name' => $data['menuName'] . '修改数据接口',
  299. 'app_name' => 'adminapi',
  300. 'cate_id' => $cateId,
  301. 'add_time' => date('Y-m-d H:i:s')
  302. ],
  303. [
  304. 'path' => $routeName . '/<id>',
  305. 'method' => 'DELETE',
  306. 'name' => $data['menuName'] . '删除数据接口',
  307. 'app_name' => 'adminapi',
  308. 'cate_id' => $cateId,
  309. 'add_time' => date('Y-m-d H:i:s')
  310. ],
  311. ];
  312. app()->make(SystemRouteServices::class)->saveAll($ruleData);
  313. //记录权限加入菜单表
  314. $menuData = [];
  315. foreach ($ruleData as $item) {
  316. $menuData[] = [
  317. 'pid' => $menuInfo->id,
  318. 'methods' => $item['method'],
  319. 'api_url' => $item['path'],
  320. 'name' => $item['name'],
  321. 'is_del' => 0,
  322. ];
  323. }
  324. $menus = app()->make(SystemMenusServices::class)->saveAll($menuData);
  325. $menuIds = array_column($menus->toArray(), 'id');
  326. array_push($menuIds, $menuInfo->id);
  327. //生成文件
  328. $make = $this->makeFile($tableName, $routeName, true, $data, $filePath);
  329. $makePath = [];
  330. foreach ($make as $key => $item) {
  331. $makePath[$key] = $item['path'];
  332. }
  333. //记录crud生成
  334. $res = $this->dao->save([
  335. 'pid' => $data['pid'],
  336. 'name' => $data['menuName'],
  337. 'table_name' => $tableName,
  338. 'table_comment' => $tableInfo['TABLE_COMMENT'] ?? '',
  339. 'table_collation' => $tableInfo['TABLE_COLLATION'] ?? '',
  340. 'field' => json_encode($data),//提交的数据
  341. 'menu_ids' => json_encode($menuIds),//生成的菜单id
  342. 'make_path' => json_encode($makePath),
  343. 'add_time' => time()
  344. ]);
  345. return $res;
  346. });
  347. return $res->toArray();
  348. }
  349. /**
  350. * 获取数据库配置
  351. * @return array
  352. */
  353. protected function getDbConfig(): array
  354. {
  355. $default = app()->config->get('database.default');
  356. $config = app()->config->get("database.connections.{$default}");
  357. if (0 == $config['deploy']) {
  358. $dbConfig = [
  359. 'adapter' => $config['type'],
  360. 'host' => $config['hostname'],
  361. 'name' => $config['database'],
  362. 'user' => $config['username'],
  363. 'pass' => $config['password'],
  364. 'port' => $config['hostport'],
  365. 'charset' => $config['charset'],
  366. 'table_prefix' => $config['prefix'],
  367. ];
  368. } else {
  369. $dbConfig = [
  370. 'adapter' => explode(',', $config['type'])[0],
  371. 'host' => explode(',', $config['hostname'])[0],
  372. 'name' => explode(',', $config['database'])[0],
  373. 'user' => explode(',', $config['username'])[0],
  374. 'pass' => explode(',', $config['password'])[0],
  375. 'port' => explode(',', $config['hostport'])[0],
  376. 'charset' => explode(',', $config['charset'])[0],
  377. 'table_prefix' => explode(',', $config['prefix'])[0],
  378. ];
  379. }
  380. $table = app()->config->get('database.migration_table', 'migrations');
  381. $dbConfig['default_migration_table'] = $dbConfig['table_prefix'] . $table;
  382. return $dbConfig;
  383. }
  384. public function getAdapter()
  385. {
  386. $options = $this->getDbConfig();
  387. $adapter = AdapterFactory::instance()->getAdapter($options['adapter'], $options);
  388. if ($adapter->hasOption('table_prefix') || $adapter->hasOption('table_suffix')) {
  389. $adapter = AdapterFactory::instance()->getWrapper('prefix', $adapter);
  390. }
  391. return $adapter;
  392. }
  393. /**
  394. * 创建数据库
  395. * @param string $tableName
  396. * @param string $tableComment
  397. * @param array $tableField
  398. * @return array
  399. * @author 等风来
  400. * @email 136327134@qq.com
  401. * @date 2023/4/7
  402. */
  403. public function makeDatebase(string $tableName, string $tableComment, array $tableField = [])
  404. {
  405. $softDelete = false;
  406. $timestamps = false;
  407. $indexField = [];
  408. //创建表
  409. $table = new Table($tableName, ['comment' => $tableComment], $this->getAdapter());
  410. //创建字段
  411. foreach ($tableField as $item) {
  412. $option = [];
  413. if (isset($item['limit'])) {
  414. $option['limit'] = (int)$item['limit'];
  415. }
  416. if (isset($item['default'])) {
  417. $option['default'] = $item['default'];
  418. }
  419. //创建伪删除
  420. if ($item['file_type'] === 'addSoftDelete') {
  421. $table->addSoftDelete();
  422. $softDelete = true;
  423. } else if ($item['file_type'] === 'addTimestamps') {
  424. //创建修改和增加时间
  425. $table->addTimestamps();
  426. $timestamps = true;
  427. } else {
  428. $option['comment'] = $item['comment'];
  429. $table->addColumn($item['field'], $this->changeTabelRule($item['file_type']), $option);
  430. }
  431. }
  432. //创建索引
  433. if (!empty($data['tableIndex'])) {
  434. $indexField = $data['tableIndex'];
  435. foreach ($data['tableIndex'] as $item) {
  436. $table->addIndex($item);
  437. }
  438. }
  439. //执行创建
  440. $table->create();
  441. return compact('indexField', 'softDelete', 'timestamps');
  442. }
  443. /**
  444. * 创建文件返回文件路径和内容
  445. * @param string $tableName
  446. * @param string $routeName
  447. * @param bool $isMake
  448. * @param array $options
  449. * @param array $filePath
  450. * @return array[]
  451. * @author 等风来
  452. * @email 136327134@qq.com
  453. * @date 2023/4/7
  454. */
  455. public function makeFile(string $tableName, string $routeName, bool $isMake = false, array $options = [], array $filePath = [])
  456. {
  457. $options['fromField'] = is_array($options['fromField']) ? $options['fromField'] : [];
  458. $options['columnField'] = is_array($options['columnField']) ? $options['columnField'] : [];
  459. //生成模型
  460. $model = app()->make(Model::class);
  461. [$modelContent, $modelPath, $usePath] = $model->setFilePathName($filePath['model'] ?? '')->isMake($isMake)->handle($tableName, $options);
  462. //生成dao
  463. $dao = app()->make(Dao::class);
  464. [$daoContent, $daoPath, $usePath] = $dao->setFilePathName($filePath['dao'] ?? '')->isMake($isMake)->handle($tableName, [
  465. 'usePath' => $usePath,
  466. ]);
  467. //生成service
  468. $service = app()->make(Service::class);
  469. [$serviceContent, $servicePath, $usePath] = $service->setFilePathName($filePath['service'] ?? '')->isMake($isMake)->handle($tableName, [
  470. 'field' => $options['fromField'],
  471. 'usePath' => $usePath,
  472. ]);
  473. //生成验证器
  474. $validate = app()->make(Validate::class);
  475. [$validateContent, $validatePath] = $validate->setFilePathName($filePath['validate'] ?? '')->isMake($isMake)->handle($tableName);
  476. //生成控制器
  477. $controller = app()->make(Controller::class);
  478. [$controllerContent, $controllerPath] = $controller->setFilePathName($filePath['controller'] ?? '')->isMake($isMake)->handle($tableName, [
  479. 'usePath' => $usePath,
  480. 'field' => array_column($options['fromField'], 'field'),
  481. ]);
  482. //生成路由
  483. $route = app()->make(Route::class);
  484. [$routeContent, $routePath] = $route->setFilePathName($filePath['route'] ?? '')->isMake($isMake)->handle($tableName, [
  485. 'menus' => $options['menuName'],
  486. 'route' => $routeName
  487. ]);
  488. //生成前台路由
  489. $viewRouter = app()->make(ViewRouter::class);
  490. [$routerContent, $routerPath] = $viewRouter->setFilePathName($filePath['router'] ?? '')->isMake($isMake)->handle($tableName, [
  491. 'route' => $routeName,
  492. 'menuName' => $options['menuName'],
  493. ]);
  494. //生成前台接口
  495. $viewApi = app()->make(ViewApi::class);
  496. [$apiContent, $apiPath] = $viewApi->setFilePathName($filePath['api'] ?? '')->isMake($isMake)->handle($tableName, [
  497. 'route' => $routeName,
  498. ]);
  499. //生成前台页面
  500. $viewPages = app()->make(ViewPages::class);
  501. [$pagesContent, $pagesPath] = $viewPages->setFilePathName($filePath['pages'] ?? '')->isMake($isMake)->handle($tableName, [
  502. 'field' => $options['columnField'],
  503. 'route' => $routeName,
  504. 'pathApiJs' => '@/' . str_replace('\\', '/', str_replace([Make::adminTemplatePath(), '.js'], '', $apiPath)),
  505. ]);
  506. return [
  507. 'controller' => [
  508. 'path' => $this->replace($controllerPath),
  509. 'content' => $controllerContent
  510. ],
  511. 'model' => [
  512. 'path' => $this->replace($modelPath),
  513. 'content' => $modelContent
  514. ],
  515. 'dao' => [
  516. 'path' => $this->replace($daoPath),
  517. 'content' => $daoContent
  518. ],
  519. 'route' => [
  520. 'path' => $this->replace($routePath),
  521. 'content' => $routeContent
  522. ],
  523. 'service' => [
  524. 'path' => $this->replace($servicePath),
  525. 'content' => $serviceContent
  526. ],
  527. 'validate' => [
  528. 'path' => $this->replace($validatePath),
  529. 'content' => $validateContent
  530. ],
  531. 'router' => [
  532. 'path' => $this->replace($routerPath),
  533. 'content' => $routerContent
  534. ],
  535. 'api' => [
  536. 'path' => $this->replace($apiPath),
  537. 'content' => $apiContent
  538. ],
  539. 'pages' => [
  540. 'path' => $this->replace($pagesPath),
  541. 'content' => $pagesContent
  542. ],
  543. ];
  544. }
  545. protected function replace(string $path)
  546. {
  547. return str_replace([app()->getRootPath(), Make::adminTemplatePath()], '', $path);
  548. }
  549. /**
  550. * @param string $tableName
  551. * @param bool $fullName
  552. * @return string
  553. * @author 等风来
  554. * @email 136327134@qq.com
  555. * @date 2023/4/7
  556. */
  557. public function getTableName(string $tableName, bool $fullName = true)
  558. {
  559. $tablePrefix = config('database.connections.mysql.prefix');
  560. $pattern = '/^' . $tablePrefix . '/i';
  561. return ($fullName ? $tablePrefix : '') . (preg_replace($pattern, '', $tableName));
  562. }
  563. }