Helper.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. <?php
  2. namespace app\admin\library\crud;
  3. use think\Exception;
  4. use think\facade\Db;
  5. use app\common\library\Menu;
  6. use app\admin\model\MenuRule;
  7. use app\admin\model\CrudLog;
  8. class Helper
  9. {
  10. /**
  11. * 内部保留词
  12. */
  13. protected static $reservedKeywords = [
  14. 'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while', 'xor', 'yield'
  15. ];
  16. /**
  17. * 预设控制器和模型文件位置
  18. */
  19. protected static $parseNamePresets = [
  20. 'controller' => [
  21. 'user' => ['user', 'user'],
  22. 'admin' => ['auth', 'admin'],
  23. 'admin_group' => ['auth', 'group'],
  24. 'attachment' => ['routine', 'attachment'],
  25. 'menu_rule' => ['auth', 'menu'],
  26. ],
  27. 'model' => [],
  28. 'validate' => [],
  29. ];
  30. /**
  31. * 子级菜单数组(权限节点)
  32. * @var string
  33. */
  34. protected static $menuChildren = [
  35. ['type' => 'button', 'title' => '查看', 'name' => '/index', 'status' => '1'],
  36. ['type' => 'button', 'title' => '添加', 'name' => '/add', 'status' => '1'],
  37. ['type' => 'button', 'title' => '编辑', 'name' => '/edit', 'status' => '1'],
  38. ['type' => 'button', 'title' => '删除', 'name' => '/del', 'status' => '1'],
  39. ['type' => 'button', 'title' => '快速排序', 'name' => '/sortable', 'status' => '1'],
  40. ];
  41. /**
  42. * 输入框类型的识别规则
  43. */
  44. protected static $inputTypeRule = [
  45. // 开关组件
  46. [
  47. 'type' => ['tinyint', 'int', 'enum'],
  48. 'suffix' => ['switch', 'toggle'],
  49. 'value' => 'switch',
  50. ],
  51. [
  52. 'column_type' => ['tinyint(1)', 'char(1)', 'tinyint(1) unsigned'],
  53. 'suffix' => ['switch', 'toggle'],
  54. 'value' => 'switch',
  55. ],
  56. // 富文本-识别规则和textarea重合,优先识别为富文本
  57. [
  58. 'type' => ['longtext', 'text', 'mediumtext', 'smalltext', 'tinytext', 'bigtext'],
  59. 'suffix' => ['content', 'editor'],
  60. 'value' => 'editor',
  61. ],
  62. // textarea
  63. [
  64. 'type' => ['varchar'],
  65. 'suffix' => ['textarea', 'multiline', 'rows'],
  66. 'value' => 'textarea',
  67. ],
  68. // Array
  69. [
  70. 'suffix' => ['array'],
  71. 'value' => 'array',
  72. ],
  73. // 时间选择器-字段类型为int同时以['time', 'datetime']结尾
  74. [
  75. 'type' => ['int'],
  76. 'suffix' => ['time', 'datetime'],
  77. 'value' => 'timestamp',
  78. ],
  79. [
  80. 'type' => ['datetime', 'timestamp'],
  81. 'value' => 'datetime',
  82. ],
  83. [
  84. 'type' => ['date'],
  85. 'value' => 'date',
  86. ],
  87. [
  88. 'type' => ['year'],
  89. 'value' => 'year',
  90. ],
  91. [
  92. 'type' => ['time'],
  93. 'value' => 'time',
  94. ],
  95. // 单选select
  96. [
  97. 'suffix' => ['select', 'list', 'data'],
  98. 'value' => 'select',
  99. ],
  100. // 多选select
  101. [
  102. 'suffix' => ['selects', 'multi', 'lists'],
  103. 'value' => 'selects',
  104. ],
  105. // 远程select
  106. [
  107. 'suffix' => ['_id'],
  108. 'value' => 'remoteSelect',
  109. ],
  110. // 远程selects
  111. [
  112. 'suffix' => ['_ids'],
  113. 'value' => 'remoteSelects',
  114. ],
  115. // 城市选择器
  116. [
  117. 'suffix' => ['city'],
  118. 'value' => 'city',
  119. ],
  120. // 单图上传
  121. [
  122. 'suffix' => ['image', 'avatar'],
  123. 'value' => 'image',
  124. ],
  125. // 多图上传
  126. [
  127. 'suffix' => ['images', 'avatars'],
  128. 'value' => 'images',
  129. ],
  130. // 文件上传
  131. [
  132. 'suffix' => ['file'],
  133. 'value' => 'file',
  134. ],
  135. // 多文件上传
  136. [
  137. 'suffix' => ['files'],
  138. 'value' => 'files',
  139. ],
  140. // icon选择器
  141. [
  142. 'suffix' => ['icon'],
  143. 'value' => 'icon',
  144. ],
  145. // 单选框
  146. [
  147. 'column_type' => ['tinyint(1)', 'char(1)', 'tinyint(1) unsigned'],
  148. 'suffix' => ['status', 'state', 'type'],
  149. 'value' => 'radio',
  150. ],
  151. // 数字输入框
  152. [
  153. 'suffix' => ['number', 'int', 'num'],
  154. 'value' => 'number',
  155. ],
  156. [
  157. 'type' => ['bigint', 'int', 'mediumint', 'smallint', 'tinyint', 'decimal', 'double', 'float'],
  158. 'value' => 'number',
  159. ],
  160. // 富文本-低权重
  161. [
  162. 'type' => ['longtext', 'text', 'mediumtext', 'smalltext', 'tinytext', 'bigtext'],
  163. 'value' => 'textarea',
  164. ],
  165. // 单选框-低权重
  166. [
  167. 'type' => ['enum'],
  168. 'value' => 'radio',
  169. ],
  170. // 多选框
  171. [
  172. 'type' => ['set'],
  173. 'value' => 'checkbox',
  174. ],
  175. // 颜色选择器
  176. [
  177. 'suffix' => ['color'],
  178. 'value' => 'color',
  179. ],
  180. ];
  181. /**
  182. * 预设WEB端文件位置
  183. */
  184. protected static $parseWebDirPresets = [
  185. 'lang' => [],
  186. 'views' => [
  187. 'user' => ['user', 'user'],
  188. 'admin' => ['auth', 'admin'],
  189. 'admin_group' => ['auth', 'group'],
  190. 'attachment' => ['routine', 'attachment'],
  191. 'menu_rule' => ['auth', 'menu'],
  192. ],
  193. ];
  194. /**
  195. * 添加时间字段
  196. * @var string
  197. */
  198. protected static $createTimeField = 'create_time';
  199. /**
  200. * 更新时间字段
  201. * @var string
  202. */
  203. protected static $updateTimeField = 'update_time';
  204. public static function getDictData(&$dict, $field, $lang, $translationPrefix = ''): array
  205. {
  206. if (!$field['comment']) return [];
  207. $comment = str_replace([',', ':'], [',', ':'], $field['comment']);
  208. if (stripos($comment, ':') !== false && stripos($comment, ',') && stripos($comment, '=') !== false) {
  209. [$fieldTitle, $item] = explode(':', $comment);
  210. $dict[$translationPrefix . $field['name']] = $lang == 'en' ? $field['name'] : $fieldTitle;
  211. foreach (explode(',', $item) as $v) {
  212. $valArr = explode('=', $v);
  213. if (count($valArr) == 2) {
  214. [$key, $value] = $valArr;
  215. $dict[$translationPrefix . $field['name'] . ' ' . $key] = $lang == 'en' ? $field['name'] . ' ' . $key : $value;
  216. }
  217. }
  218. } else {
  219. $dict[$translationPrefix . $field['name']] = $lang == 'en' ? $field['name'] : $comment;
  220. }
  221. return $dict;
  222. }
  223. public static function recordCrudStatus(array $data)
  224. {
  225. if (isset($data['id'])) {
  226. return CrudLog::where('id', $data['id'])
  227. ->update([
  228. 'status' => $data['status'],
  229. ]);
  230. }
  231. $log = CrudLog::create([
  232. 'table_name' => $data['table']['name'],
  233. 'table' => $data['table'],
  234. 'fields' => $data['fields'],
  235. 'status' => $data['status'],
  236. ]);
  237. return $log->id;
  238. }
  239. public static function createTable($name, $comment, $fields): array
  240. {
  241. $fieldType = [
  242. 'variableLength' => ['blob', 'date', 'enum', 'geometry', 'geometrycollection', 'json', 'linestring', 'longblob', 'longtext', 'mediumblob', 'mediumtext', 'multilinestring', 'multipoint', 'multipolygon', 'point', 'polygon', 'set', 'text', 'tinyblob', 'tinytext', 'year'],
  243. 'fixedLength' => ['int', 'bigint', 'binary', 'bit', 'char', 'datetime', 'mediumint', 'smallint', 'time', 'timestamp', 'tinyint', 'varbinary', 'varchar'],
  244. 'decimal' => ['decimal', 'double', 'float'],
  245. 'supportUnsigned' => ['int', 'tinyint', 'smallint', 'mediumint', 'integer', 'bigint', 'real', 'double', 'float', 'decimal', 'numeric'],
  246. ];
  247. $name = self::getTableName($name);
  248. $sql = "CREATE TABLE IF NOT EXISTS `$name` (" . PHP_EOL;
  249. $pk = '';
  250. foreach ($fields as $field) {
  251. $fieldConciseType = self::analyseFieldType($field);
  252. // 组装dateType
  253. if (!isset($field['dataType']) || !$field['dataType']) {
  254. if (!$field['type']) {
  255. continue;
  256. }
  257. if (in_array($field['type'], $fieldType['fixedLength'])) {
  258. $field['dataType'] = "{$field['type']}({$field['length']})";
  259. } elseif (in_array($field['type'], $fieldType['decimal'])) {
  260. $field['dataType'] = "{$field['type']}({$field['length']},{$field['precision']})";
  261. } elseif (in_array($field['type'], $fieldType['variableLength'])) {
  262. $field['dataType'] = $field['type'];
  263. } else {
  264. $field['dataType'] = $field['precision'] ? "{$field['type']}({$field['length']},{$field['precision']})" : "{$field['type']}({$field['length']})";
  265. }
  266. }
  267. $unsigned = ($field['unsigned'] && in_array($fieldConciseType, $fieldType['supportUnsigned'])) ? ' UNSIGNED' : '';
  268. $null = $field['null'] ? ' NULL' : ' NOT NULL';
  269. $autoIncrement = $field['autoIncrement'] ? ' AUTO_INCREMENT' : '';
  270. $default = '';
  271. if (strtolower((string)$field['default']) == 'null') {
  272. $default = ' DEFAULT NULL';
  273. } elseif ($field['default'] == '0') {
  274. $default = " DEFAULT '0'";
  275. } elseif ($field['default'] == 'empty string') {
  276. $default = " DEFAULT ''";
  277. } elseif ($field['default']) {
  278. $default = " DEFAULT '{$field['default']}'";
  279. }
  280. $fieldComment = $field['comment'] ? " COMMENT '{$field['comment']}'" : '';
  281. $sql .= "`{$field['name']}` {$field['dataType']}$unsigned$null$autoIncrement$default$fieldComment ," . PHP_EOL;
  282. if ($field['primaryKey']) {
  283. $pk = $field['name'];
  284. }
  285. }
  286. $sql .= "PRIMARY KEY (`$pk`)" . PHP_EOL . ") ";
  287. $sql .= "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='$comment'";
  288. Db::execute($sql);
  289. return [$pk];
  290. }
  291. public static function parseNameData($app, $table, $type, $value = ''): array
  292. {
  293. $pathArr = [];
  294. if ($value) {
  295. $value = str_replace('.php', '', $value);
  296. $value = str_replace(['.', '/', '\\', '_'], '/', $value);
  297. $pathArrTemp = explode('/', $value);
  298. $redundantDir = [
  299. 'app' => 0,
  300. $app => 1,
  301. $type => 2,
  302. ];
  303. foreach ($pathArrTemp as $key => $item) {
  304. if (!array_key_exists($item, $redundantDir) || $key !== $redundantDir[$item]) {
  305. $pathArr[] = $item;
  306. }
  307. }
  308. } else {
  309. if (isset(self::$parseNamePresets[$type]) && array_key_exists($table, self::$parseNamePresets[$type])) {
  310. $pathArr = self::$parseNamePresets[$type][$table];
  311. } else {
  312. $table = str_replace(['.', '/', '\\', '_'], '/', $table);
  313. $pathArr = explode('/', $table);
  314. }
  315. }
  316. $originalLastName = array_pop($pathArr);
  317. $pathArr = array_map('strtolower', $pathArr);
  318. $lastName = ucfirst($originalLastName);
  319. // 类名不能为内部关键字
  320. if (in_array(strtolower($originalLastName), self::$reservedKeywords)) {
  321. throw new Exception('Unable to use internal variable:' . $lastName);
  322. }
  323. $appDir = app()->getBasePath() . $app . DIRECTORY_SEPARATOR;
  324. $namespace = "app\\$app\\$type" . ($pathArr ? '\\' . implode('\\', $pathArr) : '');
  325. $parseFile = $appDir . $type . DIRECTORY_SEPARATOR . ($pathArr ? implode(DIRECTORY_SEPARATOR, $pathArr) . DIRECTORY_SEPARATOR : '') . $lastName . '.php';
  326. $rootFileName = $namespace . "/$lastName" . '.php';
  327. return [
  328. 'lastName' => $lastName,
  329. 'originalLastName' => $originalLastName,
  330. 'path' => $pathArr,
  331. 'namespace' => $namespace,
  332. 'parseFile' => path_transform($parseFile),
  333. 'rootFileName' => path_transform($rootFileName),
  334. ];
  335. }
  336. public static function parseWebDirNameData($table, $type, $value = ''): array
  337. {
  338. $pathArr = [];
  339. if ($value) {
  340. $value = str_replace(['.', '/', '\\', '_'], '/', $value);
  341. $pathArrTemp = explode('/', $value);
  342. $redundantDir = [
  343. 'web' => 0,
  344. 'src' => 1,
  345. 'views' => 2,
  346. 'lang' => 2,
  347. 'backend' => 3,
  348. 'pages' => 3,
  349. 'en' => 4,
  350. 'zh-cn' => 4,
  351. ];
  352. foreach ($pathArrTemp as $key => $item) {
  353. if (!array_key_exists($item, $redundantDir) || $key !== $redundantDir[$item]) {
  354. $pathArr[] = $item;
  355. }
  356. }
  357. } else {
  358. if (array_key_exists($table, self::$parseWebDirPresets[$type])) {
  359. $pathArr = self::$parseWebDirPresets[$type][$table];
  360. } else {
  361. $table = str_replace(['.', '/', '\\', '_'], '/', $table);
  362. $pathArr = explode('/', $table);
  363. }
  364. }
  365. $originalLastName = array_pop($pathArr);
  366. $pathArr = array_map('strtolower', $pathArr);
  367. $lastName = lcfirst($originalLastName);
  368. $webDir['path'] = $pathArr;
  369. $webDir['lastName'] = $lastName;
  370. $webDir['originalLastName'] = $originalLastName;
  371. if ($type == 'views') {
  372. $webDir['views'] = "web/src/views/backend" . ($pathArr ? '/' . implode('/', $pathArr) : '') . "/$lastName";
  373. } elseif ($type == 'lang') {
  374. $webDir['lang'] = array_merge($pathArr, [$lastName]);
  375. $langDir = ['en', 'zh-cn'];
  376. foreach ($langDir as $item) {
  377. $webDir[$item] = "web/src/lang/backend/$item" . ($pathArr ? '/' . implode('/', $pathArr) : '') . "/$lastName";
  378. }
  379. }
  380. foreach ($webDir as &$item) {
  381. if (is_string($item)) $item = path_transform($item);
  382. }
  383. return $webDir;
  384. }
  385. public static function getTableName(string $table, $fullName = true): string
  386. {
  387. $tablePrefix = config('database.connections.mysql.prefix');
  388. $pattern = '/^' . $tablePrefix . '/i';
  389. return ($fullName ? $tablePrefix : '') . (preg_replace($pattern, '', $table));
  390. }
  391. /**
  392. * 获取菜单name、path
  393. * @param array $webDir
  394. * @return string
  395. */
  396. public static function getMenuName(array $webDir): string
  397. {
  398. return ($webDir['path'] ? implode('/', $webDir['path']) . '/' : '') . $webDir['originalLastName'];
  399. }
  400. /**
  401. * 获取基础模板文件路径
  402. * @param string $name
  403. * @return string
  404. */
  405. public static function getStubFilePath(string $name): string
  406. {
  407. return app_path() . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'crud' . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR . path_transform($name) . '.stub';
  408. }
  409. /**
  410. * 组装模板
  411. * @param string $name
  412. * @param array $data
  413. * @param bool $escape
  414. * @return string
  415. */
  416. public static function assembleStub(string $name, array $data, bool $escape = false): string
  417. {
  418. foreach ($data as &$datum) {
  419. $datum = is_array($datum) ? implode(PHP_EOL, $datum) : $datum;
  420. }
  421. $search = $replace = [];
  422. foreach ($data as $k => $v) {
  423. $search[] = "{%$k%}";
  424. $replace[] = $v;
  425. }
  426. $stubPath = self::getStubFilePath($name);
  427. $stubContent = file_get_contents($stubPath);
  428. $content = str_replace($search, $replace, $stubContent);
  429. return $escape ? self::escape($content) : $content;
  430. }
  431. /**
  432. * 获取转义编码后的值
  433. * @param string|array $value
  434. * @return string
  435. */
  436. public static function escape($value): string
  437. {
  438. if (is_array($value)) {
  439. $value = json_encode($value, JSON_UNESCAPED_UNICODE);
  440. }
  441. return htmlspecialchars($value, ENT_QUOTES, 'UTF-8', false);
  442. }
  443. public static function tab(int $num = 1): string
  444. {
  445. return str_pad('', 4 * $num);
  446. }
  447. /**
  448. * 删除数据表
  449. */
  450. public static function delTable(string $table)
  451. {
  452. $sql = 'DROP TABLE IF EXISTS `' . self::getTableName($table) . '`';
  453. Db::execute($sql);
  454. }
  455. /**
  456. * 根据数据表解析字段数据
  457. */
  458. public static function parseTableColumns(string $table, bool $analyseField = false): array
  459. {
  460. // 从数据库中获取表字段信息
  461. $sql = 'SELECT * FROM `information_schema`.`columns` '
  462. . 'WHERE TABLE_SCHEMA = ? AND table_name = ? '
  463. . 'ORDER BY ORDINAL_POSITION';
  464. $columns = [];
  465. $tableColumn = Db::query($sql, [config('database.connections.mysql.database'), self::getTableName($table)]);
  466. foreach ($tableColumn as $item) {
  467. $isNullAble = $item['IS_NULLABLE'] == 'YES';
  468. $column = [
  469. 'name' => $item['COLUMN_NAME'],
  470. 'type' => $item['DATA_TYPE'],
  471. 'dataType' => stripos($item['COLUMN_TYPE'], '(') !== false ? substr_replace($item['COLUMN_TYPE'], '', stripos($item['COLUMN_TYPE'], ')') + 1) : $item['COLUMN_TYPE'],
  472. 'default' => ($isNullAble && is_null($item['COLUMN_DEFAULT'])) ? 'null' : $item['COLUMN_DEFAULT'],
  473. 'null' => $isNullAble,
  474. 'primaryKey' => $item['COLUMN_KEY'] == 'PRI',
  475. 'unsigned' => (bool)stripos($item['COLUMN_TYPE'], 'unsigned'),
  476. 'autoIncrement' => stripos($item['EXTRA'], 'auto_increment') !== false,
  477. 'comment' => $item['COLUMN_COMMENT'],
  478. 'designType' => self::getTableColumnsDataType($item),
  479. 'table' => [],
  480. 'form' => [],
  481. ];
  482. if ($analyseField) {
  483. self::analyseField($column);
  484. } else {
  485. self::handleTableColumn($column);
  486. }
  487. $columns[$item['COLUMN_NAME']] = $column;
  488. }
  489. return $columns;
  490. }
  491. /**
  492. * 解析到的表字段的额外处理
  493. */
  494. public static function handleTableColumn(&$column)
  495. {
  496. // 预留
  497. }
  498. public static function analyseFieldType($field): string
  499. {
  500. $dataType = (isset($field['dataType']) && $field['dataType']) ? $field['dataType'] : $field['type'];
  501. if (stripos($dataType, '(') !== false) {
  502. $typeName = explode('(', $dataType);
  503. return trim($typeName[0]);
  504. }
  505. return trim($dataType);
  506. }
  507. /**
  508. * 分析字段
  509. */
  510. public static function analyseField(&$field)
  511. {
  512. $field['type'] = self::analyseFieldType($field);
  513. $field['originalDesignType'] = $field['designType'];
  514. // 表单项类型转换对照表
  515. $designTypeComparison = [
  516. 'pk' => 'string',
  517. 'weigh' => 'number',
  518. 'timestamp' => 'datetime',
  519. 'float' => 'number',
  520. ];
  521. if (array_key_exists($field['designType'], $designTypeComparison)) {
  522. $field['designType'] = $designTypeComparison[$field['designType']];
  523. }
  524. // 是否开启了多选
  525. $supportMultipleComparison = ['select', 'image', 'file', 'remoteSelect'];
  526. if (in_array($field['designType'], $supportMultipleComparison)) {
  527. $multiKey = $field['designType'] == 'remoteSelect' ? 'select-multi' : $field['designType'] . '-multi';
  528. if (isset($field['form'][$multiKey]) && $field['form'][$multiKey]) {
  529. $field['designType'] = $field['designType'] . 's';
  530. }
  531. }
  532. }
  533. public static function getTableColumnsDataType($column)
  534. {
  535. if (stripos($column['COLUMN_NAME'], 'id') !== false && stripos($column['EXTRA'], 'auto_increment') !== false) {
  536. return 'pk';
  537. } elseif ($column['COLUMN_NAME'] == 'weigh') {
  538. return 'weigh';
  539. } elseif (in_array($column['COLUMN_NAME'], ['createtime', 'updatetime', 'create_time', 'update_time'])) {
  540. return 'timestamp';
  541. }
  542. foreach (self::$inputTypeRule as $item) {
  543. $typeBool = true;
  544. $suffixBool = true;
  545. $columnTypeBool = true;
  546. if (isset($item['type']) && $item['type'] && !in_array($column['DATA_TYPE'], $item['type'])) {
  547. $typeBool = false;
  548. }
  549. if (isset($item['suffix']) && $item['suffix']) {
  550. $suffixBool = self::isMatchSuffix($column['COLUMN_NAME'], $item['suffix']);
  551. }
  552. if (isset($item['column_type']) && $item['column_type'] && !in_array($column['COLUMN_TYPE'], $item['column_type'])) {
  553. $columnTypeBool = false;
  554. }
  555. if ($typeBool && $suffixBool && $columnTypeBool) {
  556. return $item['value'];
  557. }
  558. }
  559. return 'string';
  560. }
  561. /**
  562. * 判断是否符合指定后缀
  563. *
  564. * @param string $field 字段名称
  565. * @param mixed $suffixArr 后缀
  566. * @return bool
  567. */
  568. protected static function isMatchSuffix(string $field, $suffixArr): bool
  569. {
  570. $suffixArr = is_array($suffixArr) ? $suffixArr : explode(',', $suffixArr);
  571. foreach ($suffixArr as $v) {
  572. if (preg_match("/$v$/i", $field)) {
  573. return true;
  574. }
  575. }
  576. return false;
  577. }
  578. public static function createMenu($webViewsDir, $tableComment)
  579. {
  580. $menuName = self::getMenuName($webViewsDir);
  581. if (!MenuRule::where('name', $menuName)->value('id')) {
  582. $pid = 0;
  583. foreach ($webViewsDir['path'] as $item) {
  584. $pMenu = MenuRule::where('name', $item)->value('id');
  585. if ($pMenu) {
  586. $pid = $pMenu;
  587. continue;
  588. }
  589. $menu = [
  590. 'pid' => $pid,
  591. 'type' => 'menu_dir',
  592. 'title' => $item,
  593. 'name' => $item,
  594. 'path' => $item,
  595. ];
  596. $menu = MenuRule::create($menu);
  597. $pid = $menu->id;
  598. }
  599. // 建立菜单
  600. foreach (self::$menuChildren as &$item) {
  601. $item['name'] = $menuName . $item['name'];
  602. }
  603. $componentPath = str_replace(['\\', 'web/src'], ['/', '/src'], $webViewsDir['views'] . '/' . 'index.vue');
  604. Menu::create([
  605. [
  606. 'type' => 'menu',
  607. 'title' => $tableComment ?: $webViewsDir['originalLastName'],
  608. 'name' => $menuName,
  609. 'path' => $menuName,
  610. 'menu_type' => 'tab',
  611. 'component' => $componentPath,
  612. 'children' => self::$menuChildren,
  613. ]
  614. ], $pid);
  615. }
  616. }
  617. public static function writeWebLangFile($langData, $webLangDir)
  618. {
  619. foreach ($langData as $lang => $langDatum) {
  620. $langTsContent = '';
  621. foreach ($langDatum as $key => $item) {
  622. $quote = self::getQuote($item);
  623. $keyStr = self::formatObjectKey($key);
  624. $langTsContent .= self::tab() . $keyStr . ": $quote$item$quote,\n";
  625. }
  626. $langTsContent = "export default {\n" . $langTsContent . "}\n";
  627. self::writeFile(root_path() . $webLangDir[$lang] . '.ts', $langTsContent);
  628. }
  629. }
  630. public static function writeFile($path, $content)
  631. {
  632. $path = path_transform($path);
  633. if (!is_dir(dirname($path))) {
  634. mkdir(dirname($path), 0755, true);
  635. }
  636. return file_put_contents($path, $content);
  637. }
  638. public static function buildModelAppend($append): string
  639. {
  640. if (!$append) return '';
  641. $append = self::buildFormatSimpleArray($append);
  642. return "\n" . self::tab() . "// 追加属性" . "\n" . self::tab() . "protected \$append = $append;\n";
  643. }
  644. public static function buildModelFieldType(array $fieldType): string
  645. {
  646. if (!$fieldType) return '';
  647. $maxStrLang = 0;
  648. foreach ($fieldType as $key => $item) {
  649. $strLang = strlen($key);
  650. $maxStrLang = max($strLang, $maxStrLang);
  651. }
  652. $str = '';
  653. foreach ($fieldType as $key => $item) {
  654. $str .= self::tab(2) . "'$key'" . str_pad('=>', ($maxStrLang - strlen($key) + 3), ' ', STR_PAD_LEFT) . " '$item',\n";
  655. }
  656. return "\n" . self::tab() . "// 字段类型转换" . "\n" . self::tab() . "protected \$type = [\n" . rtrim($str, "\n") . "\n" . self::tab() . "];\n";
  657. }
  658. public static function writeModelFile(string $tablePk, array $fieldsMap, array $modelData, array $modelFile)
  659. {
  660. $modelData['pk'] = $tablePk == 'id' ? '' : "\n" . self::tab() . "// 表主键\n" . self::tab() . 'protected $pk = ' . "'$tablePk';\n" . self::tab();
  661. $modelData['autoWriteTimestamp'] = array_key_exists(self::$createTimeField, $fieldsMap) || array_key_exists(self::$updateTimeField, $fieldsMap) ? 'true' : 'false';
  662. if ($modelData['autoWriteTimestamp'] == 'true') {
  663. $modelData['createTime'] = array_key_exists(self::$createTimeField, $fieldsMap) ? '' : "\n" . self::tab() . "protected \$createTime = false;";
  664. $modelData['updateTime'] = array_key_exists(self::$updateTimeField, $fieldsMap) ? '' : "\n" . self::tab() . "protected \$updateTime = false;";
  665. }
  666. $modelMethodList = isset($modelData['relationMethodList']) ? array_merge($modelData['methods'], $modelData['relationMethodList']) : $modelData['methods'];
  667. $modelData['methods'] = $modelMethodList ? "\n" . implode("\n", $modelMethodList) : '';
  668. $modelData['append'] = self::buildModelAppend($modelData['append']);
  669. $modelData['fieldType'] = self::buildModelFieldType($modelData['fieldType']);
  670. // 生成雪花ID?
  671. if (isset($modelData['beforeInsertMixins']['snowflake'])) {
  672. // beforeInsert 组装
  673. $modelData['beforeInsert'] = Helper::assembleStub('mixins/model/beforeInsert', [
  674. 'setSnowFlakeIdCode' => $modelData['beforeInsertMixins']['snowflake']
  675. ]);
  676. }
  677. if ($modelData['afterInsert'] && $modelData['beforeInsert']) {
  678. $modelData['afterInsert'] = "\n" . $modelData['afterInsert'];
  679. }
  680. $modelFileContent = self::assembleStub('mixins/model/model', $modelData);
  681. self::writeFile($modelFile['parseFile'], $modelFileContent);
  682. }
  683. public static function writeControllerFile(array $controllerData, array $controllerFile)
  684. {
  685. if (isset($controllerData['relationVisibleFieldList']) && $controllerData['relationVisibleFieldList']) {
  686. $relationVisibleFields = '$res->visible([';
  687. foreach ($controllerData['relationVisibleFieldList'] as $cKey => $controllerDatum) {
  688. $relationVisibleFields .= "'$cKey' => ['" . implode("','", $controllerDatum) . "'],";
  689. }
  690. $relationVisibleFields = rtrim($relationVisibleFields, ',');
  691. $relationVisibleFields .= ']);';
  692. // 重写index
  693. $controllerData['methods']['index'] = self::assembleStub('mixins/controller/index', [
  694. 'relationVisibleFields' => $relationVisibleFields
  695. ]);
  696. unset($controllerData['relationVisibleFieldList']);
  697. }
  698. $controllerAttr = '';
  699. foreach ($controllerData['attr'] as $key => $item) {
  700. if (is_array($item)) {
  701. $controllerAttr .= "\n" . self::tab() . "protected \$$key = ['" . implode("', '", $item) . "'];\n";
  702. } elseif ($item) {
  703. $controllerAttr .= "\n" . self::tab() . "protected \$$key = '$item';\n";
  704. }
  705. }
  706. $controllerData['attr'] = $controllerAttr;
  707. $controllerData['initialize'] = self::assembleStub('mixins/controller/initialize', [
  708. 'modelNamespace' => $controllerData['modelNamespace'],
  709. 'modelName' => $controllerData['modelName'],
  710. 'filterRule' => $controllerData['filterRule'],
  711. ]);
  712. $contentFileContent = self::assembleStub('mixins/controller/controller', $controllerData);
  713. self::writeFile($controllerFile['parseFile'], $contentFileContent);
  714. }
  715. public static function writeFormFile($formVueData, $webViewsDir, $fields, $webTranslate)
  716. {
  717. $fieldHtml = "\n";
  718. $formVueData['bigDialog'] = $formVueData['bigDialog'] ? "\n" . self::tab(2) . 'width="50%"' : '';
  719. foreach ($formVueData['formFields'] as $field) {
  720. $fieldHtml .= self::tab(5) . "<FormItem";
  721. foreach ($field as $key => $attr) {
  722. if (is_array($attr)) {
  723. $fieldHtml .= ' ' . $key . '="' . self::getJsonFromArray($attr) . '"';
  724. } else {
  725. $fieldHtml .= ' ' . $key . '="' . $attr . '"';
  726. }
  727. }
  728. $fieldHtml .= " />\n";
  729. }
  730. $formVueData['formFields'] = rtrim($fieldHtml, "\n");
  731. // 表单验证规则
  732. $formValidatorRules = [];
  733. foreach ($fields as $field) {
  734. if (isset($field['form']['validator'])) {
  735. foreach ($field['form']['validator'] as $item) {
  736. $message = '';
  737. if (isset($field['form']['validatorMsg']) && $field['form']['validatorMsg']) {
  738. $message = ", message: '{$field['form']['validatorMsg']}'";
  739. }
  740. $formValidatorRules[$field['name']][] = "buildValidatorData({ name: '$item', title: t('$webTranslate{$field['name']}')$message })";
  741. }
  742. }
  743. }
  744. $formVueData['formItemRules'] = self::buildFormValidatorRules($formValidatorRules);
  745. $formVueContent = self::assembleStub('html/form', $formVueData);
  746. self::writeFile(root_path() . $webViewsDir['views'] . '/' . 'popupForm.vue', $formVueContent);
  747. }
  748. public static function buildFormValidatorRules($formValidatorRules): string
  749. {
  750. $rulesHtml = "";
  751. foreach ($formValidatorRules as $key => $formItemRule) {
  752. $rulesArrHtml = '';
  753. foreach ($formItemRule as $item) {
  754. $rulesArrHtml .= $item . ', ';
  755. }
  756. $rulesHtml .= self::tab() . $key . ': [' . rtrim($rulesArrHtml, ', ') . "],\n";
  757. }
  758. return $rulesHtml ? "\n" . $rulesHtml : '';
  759. }
  760. public static function writeIndexFile($indexVueData, $webViewsDir, $controllerFile)
  761. {
  762. $indexVueData['optButtons'] = self::buildSimpleArray($indexVueData['optButtons']);
  763. $indexVueData['defaultItems'] = self::getJsonFromArray($indexVueData['defaultItems']);
  764. $indexVueData['tableColumn'] = self::buildTableColumn($indexVueData['tableColumn']);
  765. $indexVueData['dblClickNotEditColumn'] = self::buildSimpleArray($indexVueData['dblClickNotEditColumn']);
  766. $controllerFile['path'][] = $controllerFile['originalLastName'];
  767. $indexVueData['controllerUrl'] = '\'/admin/' . ($controllerFile['path'] ? implode('.', $controllerFile['path']) : '') . '/\'';
  768. $indexVueData['componentName'] = ($webViewsDir['path'] ? implode('/', $webViewsDir['path']) . '/' : '') . $webViewsDir['originalLastName'];
  769. $indexVueContent = self::assembleStub('html/index', $indexVueData);
  770. self::writeFile(root_path() . $webViewsDir['views'] . '/' . 'index.vue', $indexVueContent);
  771. }
  772. public static function buildTableColumn($tableColumnList): string
  773. {
  774. $columnJson = '';
  775. foreach ($tableColumnList as $column) {
  776. $columnJson .= self::tab(3) . '{';
  777. foreach ($column as $key => $item) {
  778. $columnJson .= self::buildTableColumnKey($key, $item);
  779. }
  780. $columnJson = rtrim($columnJson, ',');
  781. $columnJson .= ' }' . ",\n";
  782. }
  783. return rtrim($columnJson, "\n");
  784. }
  785. public static function buildTableColumnKey($key, $item): string
  786. {
  787. $key = self::formatObjectKey($key);
  788. if (is_array($item)) {
  789. $itemJson = ' ' . $key . ': {';
  790. foreach ($item as $ik => $iitem) {
  791. $itemJson .= self::buildTableColumnKey($ik, $iitem);
  792. }
  793. $itemJson = rtrim($itemJson, ',');
  794. $itemJson .= ' }';
  795. } else {
  796. if ($item === 'false') {
  797. $itemJson = ' ' . $key . ': false,';
  798. } elseif (in_array($key, ['label', 'width', 'buttons'], true) || strpos($item, "t('") === 0 || strpos($item, "t(\"") === 0) {
  799. $itemJson = ' ' . $key . ': ' . $item . ',';
  800. } else {
  801. $itemJson = ' ' . $key . ': \'' . $item . '\',';
  802. }
  803. }
  804. return $itemJson;
  805. }
  806. public static function formatObjectKey(string $keyName): string
  807. {
  808. if (preg_match("/^[a-zA-Z0-9_]+$/", $keyName)) {
  809. return $keyName;
  810. } else {
  811. $quote = self::getQuote($keyName);
  812. return "$quote$keyName$quote";
  813. }
  814. }
  815. public static function getQuote(string $value): string
  816. {
  817. return stripos($value, "'") === false ? "'" : '"';
  818. }
  819. public static function buildFormatSimpleArray($arr, int $tab = 2): string
  820. {
  821. if (!$arr) return '[]';
  822. $str = '[' . PHP_EOL;
  823. foreach ($arr as $item) {
  824. if ($item == 'undefined' || $item == 'false' || is_numeric($item)) {
  825. $str .= self::tab($tab) . $item . ',' . PHP_EOL;
  826. } else {
  827. $quote = self::getQuote($item);
  828. $str .= self::tab($tab) . "$quote$item$quote," . PHP_EOL;
  829. }
  830. }
  831. return $str . self::tab($tab - 1) . ']';
  832. }
  833. public static function buildSimpleArray($arr): string
  834. {
  835. if (!$arr) return '[]';
  836. $str = '';
  837. foreach ($arr as $item) {
  838. if ($item == 'undefined' || $item == 'false' || is_numeric($item)) {
  839. $str .= $item . ', ';
  840. } else {
  841. $quote = self::getQuote($item);
  842. $str .= "$quote$item$quote, ";
  843. }
  844. }
  845. return '[' . rtrim($str, ", ") . ']';
  846. }
  847. public static function buildDefaultOrder(string $field, string $type): string
  848. {
  849. if ($field && $type) {
  850. $defaultOrderStub = [
  851. 'prop' => $field,
  852. 'order' => $type,
  853. ];
  854. $defaultOrderStub = self::getJsonFromArray($defaultOrderStub);
  855. if ($defaultOrderStub) {
  856. return "\n" . self::tab(2) . "defaultOrder: " . $defaultOrderStub . ',';
  857. }
  858. }
  859. return '';
  860. }
  861. public static function getJsonFromArray($arr)
  862. {
  863. if (is_array($arr)) {
  864. $jsonStr = '';
  865. foreach ($arr as $key => $item) {
  866. $keyStr = ' ' . self::formatObjectKey($key) . ': ';
  867. if (is_array($item)) {
  868. $jsonStr .= $keyStr . self::getJsonFromArray($item) . ',';
  869. } elseif ($item === 'false' || $item === 'true') {
  870. $jsonStr .= $keyStr . ($item === 'false' ? 'false' : 'true') . ',';
  871. } elseif ($item === null) {
  872. $jsonStr .= $keyStr . 'null,';
  873. } elseif (strpos($item, "t('") === 0 || strpos($item, "t(\"") === 0 || $item == '[]' || in_array(gettype($item), ['integer', 'double'])) {
  874. $jsonStr .= $keyStr . $item . ',';
  875. } elseif (isset($item[0]) && $item[0] == '[' && substr($item, -1, 1) == ']') {
  876. $jsonStr .= $keyStr . $item . ',';
  877. } else {
  878. $quote = self::getQuote($item);
  879. $jsonStr .= $keyStr . "$quote$item$quote,";
  880. }
  881. }
  882. return $jsonStr ? '{' . rtrim($jsonStr, ',') . ' }' : '{}';
  883. } else {
  884. return $arr;
  885. }
  886. }
  887. }