Helper.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  1. <?php
  2. namespace app\admin\library\crud;
  3. use Throwable;
  4. use ba\Filesystem;
  5. use think\Exception;
  6. use ba\TableManager;
  7. use think\facade\Db;
  8. use app\common\library\Menu;
  9. use app\admin\model\AdminRule;
  10. use app\admin\model\CrudLog;
  11. use ba\Exception as BaException;
  12. use Phinx\Db\Adapter\MysqlAdapter;
  13. use Phinx\Db\Adapter\AdapterInterface;
  14. class Helper
  15. {
  16. /**
  17. * 内部保留词
  18. * @var array
  19. */
  20. protected static array $reservedKeywords = [
  21. 'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone',
  22. 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty',
  23. 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends',
  24. 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once',
  25. 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private',
  26. 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try',
  27. 'unset', 'use', 'var', 'while', 'xor', 'yield', 'match', 'readonly', 'fn',
  28. ];
  29. /**
  30. * 预设控制器和模型文件位置
  31. * @var array
  32. */
  33. protected static array $parseNamePresets = [
  34. 'controller' => [
  35. 'user' => ['user', 'user'],
  36. 'admin' => ['auth', 'admin'],
  37. 'admin_group' => ['auth', 'group'],
  38. 'attachment' => ['routine', 'attachment'],
  39. 'admin_rule' => ['auth', 'rule'],
  40. ],
  41. 'model' => [],
  42. 'validate' => [],
  43. ];
  44. /**
  45. * 子级菜单数组(权限节点)
  46. * @var array
  47. */
  48. protected static array $menuChildren = [
  49. ['type' => 'button', 'title' => '查看', 'name' => '/index', 'status' => 1],
  50. ['type' => 'button', 'title' => '添加', 'name' => '/add', 'status' => 1],
  51. ['type' => 'button', 'title' => '编辑', 'name' => '/edit', 'status' => 1],
  52. ['type' => 'button', 'title' => '删除', 'name' => '/del', 'status' => 1],
  53. ['type' => 'button', 'title' => '快速排序', 'name' => '/sortable', 'status' => 1],
  54. ];
  55. /**
  56. * 输入框类型的识别规则
  57. * @var array
  58. */
  59. protected static array $inputTypeRule = [
  60. // 开关组件
  61. [
  62. 'type' => ['tinyint', 'int', 'enum'],
  63. 'suffix' => ['switch', 'toggle'],
  64. 'value' => 'switch',
  65. ],
  66. [
  67. 'column_type' => ['tinyint(1)', 'char(1)', 'tinyint(1) unsigned'],
  68. 'suffix' => ['switch', 'toggle'],
  69. 'value' => 'switch',
  70. ],
  71. // 富文本-识别规则和textarea重合,优先识别为富文本
  72. [
  73. 'type' => ['longtext', 'text', 'mediumtext', 'smalltext', 'tinytext', 'bigtext'],
  74. 'suffix' => ['content', 'editor'],
  75. 'value' => 'editor',
  76. ],
  77. // textarea
  78. [
  79. 'type' => ['varchar'],
  80. 'suffix' => ['textarea', 'multiline', 'rows'],
  81. 'value' => 'textarea',
  82. ],
  83. // Array
  84. [
  85. 'suffix' => ['array'],
  86. 'value' => 'array',
  87. ],
  88. // 时间选择器-字段类型为int同时以['time', 'datetime']结尾
  89. [
  90. 'type' => ['int'],
  91. 'suffix' => ['time', 'datetime'],
  92. 'value' => 'timestamp',
  93. ],
  94. [
  95. 'type' => ['datetime', 'timestamp'],
  96. 'value' => 'datetime',
  97. ],
  98. [
  99. 'type' => ['date'],
  100. 'value' => 'date',
  101. ],
  102. [
  103. 'type' => ['year'],
  104. 'value' => 'year',
  105. ],
  106. [
  107. 'type' => ['time'],
  108. 'value' => 'time',
  109. ],
  110. // 单选select
  111. [
  112. 'suffix' => ['select', 'list', 'data'],
  113. 'value' => 'select',
  114. ],
  115. // 多选select
  116. [
  117. 'suffix' => ['selects', 'multi', 'lists'],
  118. 'value' => 'selects',
  119. ],
  120. // 远程select
  121. [
  122. 'suffix' => ['_id'],
  123. 'value' => 'remoteSelect',
  124. ],
  125. // 远程selects
  126. [
  127. 'suffix' => ['_ids'],
  128. 'value' => 'remoteSelects',
  129. ],
  130. // 城市选择器
  131. [
  132. 'suffix' => ['city'],
  133. 'value' => 'city',
  134. ],
  135. // 单图上传
  136. [
  137. 'suffix' => ['image', 'avatar'],
  138. 'value' => 'image',
  139. ],
  140. // 多图上传
  141. [
  142. 'suffix' => ['images', 'avatars'],
  143. 'value' => 'images',
  144. ],
  145. // 文件上传
  146. [
  147. 'suffix' => ['file'],
  148. 'value' => 'file',
  149. ],
  150. // 多文件上传
  151. [
  152. 'suffix' => ['files'],
  153. 'value' => 'files',
  154. ],
  155. // icon选择器
  156. [
  157. 'suffix' => ['icon'],
  158. 'value' => 'icon',
  159. ],
  160. // 单选框
  161. [
  162. 'column_type' => ['tinyint(1)', 'char(1)', 'tinyint(1) unsigned'],
  163. 'suffix' => ['status', 'state', 'type'],
  164. 'value' => 'radio',
  165. ],
  166. // 数字输入框
  167. [
  168. 'suffix' => ['number', 'int', 'num'],
  169. 'value' => 'number',
  170. ],
  171. [
  172. 'type' => ['bigint', 'int', 'mediumint', 'smallint', 'tinyint', 'decimal', 'double', 'float'],
  173. 'value' => 'number',
  174. ],
  175. // 富文本-低权重
  176. [
  177. 'type' => ['longtext', 'text', 'mediumtext', 'smalltext', 'tinytext', 'bigtext'],
  178. 'value' => 'textarea',
  179. ],
  180. // 单选框-低权重
  181. [
  182. 'type' => ['enum'],
  183. 'value' => 'radio',
  184. ],
  185. // 多选框
  186. [
  187. 'type' => ['set'],
  188. 'value' => 'checkbox',
  189. ],
  190. // 颜色选择器
  191. [
  192. 'suffix' => ['color'],
  193. 'value' => 'color',
  194. ],
  195. ];
  196. /**
  197. * 预设WEB端文件位置
  198. * @var array
  199. */
  200. protected static array $parseWebDirPresets = [
  201. 'lang' => [],
  202. 'views' => [
  203. 'user' => ['user', 'user'],
  204. 'admin' => ['auth', 'admin'],
  205. 'admin_group' => ['auth', 'group'],
  206. 'attachment' => ['routine', 'attachment'],
  207. 'admin_rule' => ['auth', 'rule'],
  208. ],
  209. ];
  210. /**
  211. * 添加时间字段
  212. * @var string
  213. */
  214. protected static string $createTimeField = 'create_time';
  215. /**
  216. * 更新时间字段
  217. * @var string
  218. */
  219. protected static string $updateTimeField = 'update_time';
  220. /**
  221. * 属性的类型对照表
  222. * @var array
  223. */
  224. protected static array $attrType = [
  225. 'controller' => [
  226. 'preExcludeFields' => 'array|string',
  227. 'quickSearchField' => 'string|array',
  228. 'withJoinTable' => 'array',
  229. 'defaultSortField' => 'string|array',
  230. 'weighField' => 'string',
  231. ],
  232. ];
  233. /**
  234. * 获取字段字典数据
  235. * @param array $dict 存储字典数据的变量
  236. * @param array $field 字段数据
  237. * @param string $lang 语言
  238. * @param string $translationPrefix 翻译前缀
  239. */
  240. public static function getDictData(array &$dict, array $field, string $lang, string $translationPrefix = ''): array
  241. {
  242. if (!$field['comment']) return [];
  243. $comment = str_replace([',', ':'], [',', ':'], $field['comment']);
  244. if (stripos($comment, ':') !== false && stripos($comment, ',') && stripos($comment, '=') !== false) {
  245. [$fieldTitle, $item] = explode(':', $comment);
  246. $dict[$translationPrefix . $field['name']] = $lang == 'en' ? $field['name'] : $fieldTitle;
  247. foreach (explode(',', $item) as $v) {
  248. $valArr = explode('=', $v);
  249. if (count($valArr) == 2) {
  250. [$key, $value] = $valArr;
  251. $dict[$translationPrefix . $field['name'] . ' ' . $key] = $lang == 'en' ? $field['name'] . ' ' . $key : $value;
  252. }
  253. }
  254. } else {
  255. $dict[$translationPrefix . $field['name']] = $lang == 'en' ? $field['name'] : $comment;
  256. }
  257. return $dict;
  258. }
  259. /**
  260. * 记录CRUD状态
  261. * @param array $data CRUD记录数据
  262. * @return int 记录ID
  263. */
  264. public static function recordCrudStatus(array $data): int
  265. {
  266. if (isset($data['id'])) {
  267. CrudLog::where('id', $data['id'])
  268. ->update([
  269. 'status' => $data['status'],
  270. ]);
  271. return $data['id'];
  272. }
  273. $connection = $data['table']['databaseConnection'] ?: config('database.default');
  274. $log = CrudLog::create([
  275. 'table_name' => $data['table']['name'],
  276. 'comment' => $data['table']['comment'],
  277. 'table' => $data['table'],
  278. 'fields' => $data['fields'],
  279. 'connection' => $connection,
  280. 'status' => $data['status'],
  281. ]);
  282. return $log->id;
  283. }
  284. /**
  285. * 获取 Phinx 的字段类型数据
  286. * @param string $type 字段类型
  287. * @param array $field 字段数据
  288. * @return array
  289. */
  290. public static function getPhinxFieldType(string $type, array $field): array
  291. {
  292. if ($type == 'tinyint') {
  293. if (
  294. (isset($field['dataType']) && $field['dataType'] == 'tinyint(1)') ||
  295. ($field['default'] == '1' && $field['defaultType'] == 'INPUT')
  296. ) {
  297. $type = 'boolean';
  298. }
  299. }
  300. $phinxFieldTypeMap = [
  301. // 数字
  302. 'tinyint' => ['type' => AdapterInterface::PHINX_TYPE_INTEGER, 'limit' => MysqlAdapter::INT_TINY],
  303. 'smallint' => ['type' => AdapterInterface::PHINX_TYPE_INTEGER, 'limit' => MysqlAdapter::INT_SMALL],
  304. 'mediumint' => ['type' => AdapterInterface::PHINX_TYPE_INTEGER, 'limit' => MysqlAdapter::INT_MEDIUM],
  305. 'int' => ['type' => AdapterInterface::PHINX_TYPE_INTEGER, 'limit' => null],
  306. 'bigint' => ['type' => AdapterInterface::PHINX_TYPE_BIG_INTEGER, 'limit' => null],
  307. 'boolean' => ['type' => AdapterInterface::PHINX_TYPE_BOOLEAN, 'limit' => null],
  308. // 文本
  309. 'varchar' => ['type' => AdapterInterface::PHINX_TYPE_STRING, 'limit' => null],
  310. 'tinytext' => ['type' => AdapterInterface::PHINX_TYPE_TEXT, 'limit' => MysqlAdapter::TEXT_TINY],
  311. 'mediumtext' => ['type' => AdapterInterface::PHINX_TYPE_TEXT, 'limit' => MysqlAdapter::TEXT_MEDIUM],
  312. 'longtext' => ['type' => AdapterInterface::PHINX_TYPE_TEXT, 'limit' => MysqlAdapter::TEXT_LONG],
  313. 'tinyblob' => ['type' => AdapterInterface::PHINX_TYPE_BLOB, 'limit' => MysqlAdapter::BLOB_TINY],
  314. 'mediumblob' => ['type' => AdapterInterface::PHINX_TYPE_BLOB, 'limit' => MysqlAdapter::BLOB_MEDIUM],
  315. 'longblob' => ['type' => AdapterInterface::PHINX_TYPE_BLOB, 'limit' => MysqlAdapter::BLOB_LONG],
  316. ];
  317. return array_key_exists($type, $phinxFieldTypeMap) ? $phinxFieldTypeMap[$type] : ['type' => $type, 'limit' => null];
  318. }
  319. /**
  320. * 分析字段limit和精度
  321. * @param string $type 字段类型
  322. * @param array $field 字段数据
  323. * @return array ['limit' => 10, 'precision' => null, 'scale' => null]
  324. */
  325. public static function analyseFieldLimit(string $type, array $field): array
  326. {
  327. $fieldType = [
  328. 'decimal' => ['decimal', 'double', 'float'],
  329. 'values' => ['enum', 'set'],
  330. ];
  331. $dataTypeLimit = self::dataTypeLimit($field['dataType'] ?? '');
  332. if (in_array($type, $fieldType['decimal'])) {
  333. if ($dataTypeLimit) {
  334. return ['precision' => $dataTypeLimit[0], 'scale' => $dataTypeLimit[1] ?? 0];
  335. }
  336. $scale = isset($field['precision']) ? intval($field['precision']) : 0;
  337. return ['precision' => $field['length'] ?? 10, 'scale' => $scale];
  338. } elseif (in_array($type, $fieldType['values'])) {
  339. foreach ($dataTypeLimit as &$item) {
  340. $item = str_replace(['"', "'"], '', $item);
  341. }
  342. return ['values' => $dataTypeLimit];
  343. } elseif ($dataTypeLimit && $dataTypeLimit[0]) {
  344. return ['limit' => $dataTypeLimit[0]];
  345. } elseif (isset($field['length'])) {
  346. return ['limit' => $field['length']];
  347. }
  348. return [];
  349. }
  350. public static function dataTypeLimit(string $dataType): array
  351. {
  352. preg_match("/\((.*?)\)/", $dataType, $matches);
  353. if (isset($matches[1]) && $matches[1]) {
  354. return explode(',', trim($matches[1], ','));
  355. }
  356. return [];
  357. }
  358. public static function analyseFieldDefault(array $field): mixed
  359. {
  360. return match ($field['defaultType']) {
  361. 'EMPTY STRING' => '',
  362. 'NULL' => null,
  363. default => $field['default'],
  364. };
  365. }
  366. public static function searchArray($fields, callable $myFunction): array|bool
  367. {
  368. foreach ($fields as $key => $field) {
  369. if (call_user_func($myFunction, $field, $key)) {
  370. return $field;
  371. }
  372. }
  373. return false;
  374. }
  375. /**
  376. * 获取 Phinx 格式的字段数据
  377. * @param array $field
  378. * @return array
  379. */
  380. public static function getPhinxFieldData(array $field): array
  381. {
  382. $conciseType = self::analyseFieldType($field);
  383. $phinxTypeData = self::getPhinxFieldType($conciseType, $field);
  384. $phinxColumnOptions = self::analyseFieldLimit($conciseType, $field);
  385. if (!is_null($phinxTypeData['limit'])) {
  386. $phinxColumnOptions['limit'] = $phinxTypeData['limit'];
  387. }
  388. // 无默认值字段
  389. $noDefaultValueFields = [
  390. 'text', 'blob', 'geometry', 'geometrycollection', 'json', 'linestring', 'longblob', 'longtext', 'mediumblob',
  391. 'mediumtext', 'multilinestring', 'multipoint', 'multipolygon', 'point', 'polygon', 'tinyblob',
  392. ];
  393. if ($field['defaultType'] != 'NONE' && !in_array($conciseType, $noDefaultValueFields)) {
  394. $phinxColumnOptions['default'] = self::analyseFieldDefault($field);
  395. }
  396. $phinxColumnOptions['null'] = (bool)$field['null'];
  397. $phinxColumnOptions['comment'] = $field['comment'];
  398. $phinxColumnOptions['signed'] = !$field['unsigned'];
  399. $phinxColumnOptions['identity'] = $field['autoIncrement'];
  400. return [
  401. 'type' => $phinxTypeData['type'],
  402. 'options' => $phinxColumnOptions,
  403. ];
  404. }
  405. /**
  406. * 表字段排序
  407. * @param string $tableName 表名
  408. * @param array $fields 字段数据
  409. * @param array $designChange 前端字段改变数据
  410. * @param ?string $connection 数据库连接标识
  411. * @return void
  412. * @throws Throwable
  413. */
  414. public static function updateFieldOrder(string $tableName, array $fields, array $designChange, ?string $connection = null): void
  415. {
  416. if ($designChange) {
  417. $table = TableManager::phinxTable($tableName, [], false, $connection);
  418. foreach ($designChange as $item) {
  419. if (!$item['sync']) continue;
  420. if (!empty($item['after'])) {
  421. $fieldName = in_array($item['type'], ['add-field', 'change-field-name']) ? $item['newName'] : $item['oldName'];
  422. $field = self::searchArray($fields, function ($field) use ($fieldName) {
  423. return $field['name'] == $fieldName;
  424. });
  425. $phinxFieldData = self::getPhinxFieldData($field);
  426. // 字段顺序调整
  427. if ($item['after'] == 'FIRST FIELD') {
  428. $phinxFieldData['options']['after'] = MysqlAdapter::FIRST;
  429. } else {
  430. $phinxFieldData['options']['after'] = $item['after'];
  431. }
  432. $table->changeColumn($fieldName, $phinxFieldData['type'], $phinxFieldData['options']);
  433. }
  434. }
  435. $table->update();
  436. }
  437. }
  438. /**
  439. * 表设计处理
  440. * @param array $table 表数据
  441. * @param array $fields 字段数据
  442. * @return array
  443. * @throws Throwable
  444. */
  445. public static function handleTableDesign(array $table, array $fields): array
  446. {
  447. $name = TableManager::tableName($table['name'], true, $table['databaseConnection']);
  448. $comment = $table['comment'] ?? '';
  449. $designChange = $table['designChange'] ?? [];
  450. $adapter = TableManager::phinxAdapter(false, $table['databaseConnection']);
  451. $pk = self::searchArray($fields, function ($item) {
  452. return $item['primaryKey'];
  453. });
  454. $pk = $pk ? $pk['name'] : '';
  455. if ($adapter->hasTable($name)) {
  456. // 更新表
  457. if ($designChange) {
  458. $tableManager = TableManager::phinxTable($name, [], false, $table['databaseConnection']);
  459. $tableManager->changeComment($comment)->update();
  460. // 改名和删除操作优先
  461. $priorityOpt = false;
  462. foreach ($designChange as $item) {
  463. if (!$item['sync']) continue;
  464. if (in_array($item['type'], ['change-field-name', 'del-field']) && !$tableManager->hasColumn($item['oldName'])) {
  465. // 字段不存在
  466. throw new BaException(__($item['type'] . ' fail not exist', [$item['oldName']]));
  467. }
  468. if ($item['type'] == 'change-field-name') {
  469. $priorityOpt = true;
  470. $tableManager->renameColumn($item['oldName'], $item['newName']);
  471. } elseif ($item['type'] == 'del-field') {
  472. $priorityOpt = true;
  473. $tableManager->removeColumn($item['oldName']);
  474. }
  475. }
  476. // 保存需要优先执行的操作,避免先改名再改属性时找不到字段
  477. if ($priorityOpt) {
  478. $tableManager->update();
  479. }
  480. // 修改字段属性和添加字段操作
  481. foreach ($designChange as $item) {
  482. if (!$item['sync']) continue;
  483. if ($item['type'] == 'change-field-attr') {
  484. if (!$tableManager->hasColumn($item['oldName'])) {
  485. // 字段不存在
  486. throw new BaException(__($item['type'] . ' fail not exist', [$item['oldName']]));
  487. }
  488. $phinxFieldData = self::getPhinxFieldData(self::searchArray($fields, function ($field) use ($item) {
  489. return $field['name'] == $item['oldName'];
  490. }));
  491. $tableManager->changeColumn($item['oldName'], $phinxFieldData['type'], $phinxFieldData['options']);
  492. } elseif ($item['type'] == 'add-field') {
  493. if ($tableManager->hasColumn($item['newName'])) {
  494. // 字段已经存在
  495. throw new BaException(__($item['type'] . ' fail exist', [$item['newName']]));
  496. }
  497. $phinxFieldData = self::getPhinxFieldData(self::searchArray($fields, function ($field) use ($item) {
  498. return $field['name'] == $item['newName'];
  499. }));
  500. $tableManager->addColumn($item['newName'], $phinxFieldData['type'], $phinxFieldData['options']);
  501. }
  502. }
  503. $tableManager->update();
  504. // 表更新结构完成再处理字段排序
  505. self::updateFieldOrder($name, $fields, $designChange, $table['databaseConnection']);
  506. }
  507. } else {
  508. // 创建表
  509. $tableManager = TableManager::phinxTable($name, [
  510. 'id' => false,
  511. 'comment' => $comment,
  512. 'row_format' => 'DYNAMIC',
  513. 'primary_key' => $pk,
  514. 'collation' => 'utf8mb4_unicode_ci',
  515. ], false, $table['databaseConnection']);
  516. foreach ($fields as $field) {
  517. $phinxFieldData = self::getPhinxFieldData($field);
  518. $tableManager->addColumn($field['name'], $phinxFieldData['type'], $phinxFieldData['options']);
  519. }
  520. $tableManager->create();
  521. }
  522. return [$pk];
  523. }
  524. /**
  525. * 解析文件数据
  526. * @throws Throwable
  527. */
  528. public static function parseNameData($app, $table, $type, $value = ''): array
  529. {
  530. $pathArr = [];
  531. if ($value) {
  532. $value = str_replace('.php', '', $value);
  533. $value = str_replace(['.', '/', '\\', '_'], '/', $value);
  534. $pathArrTemp = explode('/', $value);
  535. $redundantDir = [
  536. 'app' => 0,
  537. $app => 1,
  538. $type => 2,
  539. ];
  540. foreach ($pathArrTemp as $key => $item) {
  541. if (!array_key_exists($item, $redundantDir) || $key !== $redundantDir[$item]) {
  542. $pathArr[] = $item;
  543. }
  544. }
  545. } elseif (isset(self::$parseNamePresets[$type]) && array_key_exists($table, self::$parseNamePresets[$type])) {
  546. $pathArr = self::$parseNamePresets[$type][$table];
  547. } else {
  548. $table = str_replace(['.', '/', '\\', '_'], '/', $table);
  549. $pathArr = explode('/', $table);
  550. }
  551. $originalLastName = array_pop($pathArr);
  552. $pathArr = array_map('strtolower', $pathArr);
  553. $lastName = ucfirst($originalLastName);
  554. // 类名不能为内部关键字
  555. if (in_array(strtolower($originalLastName), self::$reservedKeywords)) {
  556. throw new Exception('Unable to use internal variable:' . $lastName);
  557. }
  558. $appDir = app()->getBasePath() . $app . DIRECTORY_SEPARATOR;
  559. $namespace = "app\\$app\\$type" . ($pathArr ? '\\' . implode('\\', $pathArr) : '');
  560. $parseFile = $appDir . $type . DIRECTORY_SEPARATOR . ($pathArr ? implode(DIRECTORY_SEPARATOR, $pathArr) . DIRECTORY_SEPARATOR : '') . $lastName . '.php';
  561. $rootFileName = $namespace . "/$lastName" . '.php';
  562. return [
  563. 'lastName' => $lastName,
  564. 'originalLastName' => $originalLastName,
  565. 'path' => $pathArr,
  566. 'namespace' => $namespace,
  567. 'parseFile' => Filesystem::fsFit($parseFile),
  568. 'rootFileName' => Filesystem::fsFit($rootFileName),
  569. ];
  570. }
  571. public static function parseWebDirNameData($table, $type, $value = ''): array
  572. {
  573. $pathArr = [];
  574. if ($value) {
  575. $value = str_replace(['.', '/', '\\', '_'], '/', $value);
  576. $pathArrTemp = explode('/', $value);
  577. $redundantDir = [
  578. 'web' => 0,
  579. 'src' => 1,
  580. 'views' => 2,
  581. 'lang' => 2,
  582. 'backend' => 3,
  583. 'pages' => 3,
  584. 'en' => 4,
  585. 'zh-cn' => 4,
  586. ];
  587. foreach ($pathArrTemp as $key => $item) {
  588. if (!array_key_exists($item, $redundantDir) || $key !== $redundantDir[$item]) {
  589. $pathArr[] = $item;
  590. }
  591. }
  592. } elseif (array_key_exists($table, self::$parseWebDirPresets[$type])) {
  593. $pathArr = self::$parseWebDirPresets[$type][$table];
  594. } else {
  595. $table = str_replace(['.', '/', '\\', '_'], '/', $table);
  596. $pathArr = explode('/', $table);
  597. }
  598. $originalLastName = array_pop($pathArr);
  599. $pathArr = array_map('strtolower', $pathArr);
  600. $lastName = lcfirst($originalLastName);
  601. $webDir['path'] = $pathArr;
  602. $webDir['lastName'] = $lastName;
  603. $webDir['originalLastName'] = $originalLastName;
  604. if ($type == 'views') {
  605. $webDir['views'] = "web/src/views/backend" . ($pathArr ? '/' . implode('/', $pathArr) : '') . "/$lastName";
  606. } elseif ($type == 'lang') {
  607. $webDir['lang'] = array_merge($pathArr, [$lastName]);
  608. $langDir = ['en', 'zh-cn'];
  609. foreach ($langDir as $item) {
  610. $webDir[$item] = "web/src/lang/backend/$item" . ($pathArr ? '/' . implode('/', $pathArr) : '') . "/$lastName";
  611. }
  612. }
  613. foreach ($webDir as &$item) {
  614. if (is_string($item)) $item = Filesystem::fsFit($item);
  615. }
  616. return $webDir;
  617. }
  618. /**
  619. * 获取菜单name、path
  620. * @param array $webDir
  621. * @return string
  622. */
  623. public static function getMenuName(array $webDir): string
  624. {
  625. return ($webDir['path'] ? implode('/', $webDir['path']) . '/' : '') . $webDir['originalLastName'];
  626. }
  627. /**
  628. * 获取基础模板文件路径
  629. * @param string $name
  630. * @return string
  631. */
  632. public static function getStubFilePath(string $name): string
  633. {
  634. return app_path() . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'crud' . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR . Filesystem::fsFit($name) . '.stub';
  635. }
  636. /**
  637. * 多维数组转字符串
  638. */
  639. public static function arrayToString(array|string $value): string
  640. {
  641. if (!is_array($value)) {
  642. return $value;
  643. }
  644. foreach ($value as &$item) {
  645. $item = self::arrayToString($item);
  646. }
  647. return implode(PHP_EOL, $value);
  648. }
  649. /**
  650. * 组装模板
  651. * @param string $name
  652. * @param array $data
  653. * @param bool $escape
  654. * @return string
  655. */
  656. public static function assembleStub(string $name, array $data, bool $escape = false): string
  657. {
  658. foreach ($data as &$datum) {
  659. $datum = self::arrayToString($datum);
  660. }
  661. $search = $replace = [];
  662. foreach ($data as $k => $v) {
  663. $search[] = "{%$k%}";
  664. $replace[] = $v;
  665. }
  666. $stubPath = self::getStubFilePath($name);
  667. $stubContent = file_get_contents($stubPath);
  668. $content = str_replace($search, $replace, $stubContent);
  669. return $escape ? self::escape($content) : $content;
  670. }
  671. /**
  672. * 获取转义编码后的值
  673. * @param array|string $value
  674. * @return string
  675. */
  676. public static function escape(array|string $value): string
  677. {
  678. if (is_array($value)) {
  679. $value = json_encode($value, JSON_UNESCAPED_UNICODE);
  680. }
  681. return htmlspecialchars($value, ENT_QUOTES, 'UTF-8', false);
  682. }
  683. public static function tab(int $num = 1): string
  684. {
  685. return str_pad('', 4 * $num);
  686. }
  687. /**
  688. * 根据数据表解析字段数据
  689. * @throws Throwable
  690. */
  691. public static function parseTableColumns(string $table, bool $analyseField = false, ?string $connection = null): array
  692. {
  693. $connection = TableManager::getConnection($connection);
  694. $connectionConfig = TableManager::getConnectionConfig($connection);
  695. // 从数据库中获取表字段信息
  696. $sql = 'SELECT * FROM `information_schema`.`columns` '
  697. . 'WHERE TABLE_SCHEMA = ? AND table_name = ? '
  698. . 'ORDER BY ORDINAL_POSITION';
  699. $columns = [];
  700. $tableColumn = Db::connect($connection)->query($sql, [$connectionConfig['database'], TableManager::tableName($table, true, $connection)]);
  701. foreach ($tableColumn as $item) {
  702. $isNullAble = $item['IS_NULLABLE'] == 'YES';
  703. if (str_contains($item['COLUMN_TYPE'], '(')) {
  704. $dataType = substr_replace($item['COLUMN_TYPE'], '', stripos($item['COLUMN_TYPE'], ')') + 1);
  705. } else {
  706. $dataType = str_replace(' unsigned', '', $item['COLUMN_TYPE']);
  707. }
  708. // 默认值和默认值类型分析
  709. $default = '';
  710. if ($isNullAble && is_null($item['COLUMN_DEFAULT'])) {
  711. $defaultType = 'NULL';
  712. } elseif ($item['COLUMN_DEFAULT'] == '' && in_array($item['DATA_TYPE'], ['varchar', 'char'])) {
  713. $defaultType = 'EMPTY STRING';
  714. } elseif (!$isNullAble && is_null($item['COLUMN_DEFAULT'])) {
  715. $defaultType = 'NONE';
  716. } else {
  717. $defaultType = 'INPUT';
  718. $default = $item['COLUMN_DEFAULT'];
  719. }
  720. $column = [
  721. 'name' => $item['COLUMN_NAME'],
  722. 'type' => $item['DATA_TYPE'],
  723. 'dataType' => $dataType,
  724. 'default' => $default,
  725. 'defaultType' => $defaultType,
  726. 'null' => $isNullAble,
  727. 'primaryKey' => $item['COLUMN_KEY'] == 'PRI',
  728. 'unsigned' => (bool)stripos($item['COLUMN_TYPE'], 'unsigned'),
  729. 'autoIncrement' => stripos($item['EXTRA'], 'auto_increment') !== false,
  730. 'comment' => $item['COLUMN_COMMENT'],
  731. 'designType' => self::getTableColumnsDataType($item),
  732. 'table' => [],
  733. 'form' => [],
  734. ];
  735. if ($analyseField) {
  736. self::analyseField($column);
  737. } else {
  738. self::handleTableColumn($column);
  739. }
  740. $columns[$item['COLUMN_NAME']] = $column;
  741. }
  742. return $columns;
  743. }
  744. /**
  745. * 解析到的表字段的额外处理
  746. */
  747. public static function handleTableColumn(&$column): void
  748. {
  749. // 预留
  750. }
  751. /**
  752. * 分析字段数据类型
  753. * @param array $field 字段数据
  754. * @return string 字段类型
  755. */
  756. public static function analyseFieldType(array $field): string
  757. {
  758. $dataType = (isset($field['dataType']) && $field['dataType']) ? $field['dataType'] : $field['type'];
  759. if (stripos($dataType, '(') !== false) {
  760. $typeName = explode('(', $dataType);
  761. return trim($typeName[0]);
  762. }
  763. return trim($dataType);
  764. }
  765. /**
  766. * 分析字段的完整数据类型定义
  767. * @param array $field 字段数据
  768. * @return string
  769. */
  770. public static function analyseFieldDataType(array $field): string
  771. {
  772. if (!empty($field['dataType'])) return $field['dataType'];
  773. $conciseType = self::analyseFieldType($field);
  774. $limit = self::analyseFieldLimit($conciseType, $field);
  775. if (isset($limit['precision'])) {
  776. $dataType = "$conciseType({$limit['precision']}, {$limit['scale']})";
  777. } elseif (isset($limit['values'])) {
  778. $values = implode(',', $limit['values']);
  779. $dataType = "$conciseType($values)";
  780. } else {
  781. $dataType = "$conciseType({$limit['limit']})";
  782. }
  783. return $dataType;
  784. }
  785. /**
  786. * 分析字段
  787. */
  788. public static function analyseField(&$field): void
  789. {
  790. $field['type'] = self::analyseFieldType($field);
  791. $field['originalDesignType'] = $field['designType'];
  792. // 表单项类型转换对照表
  793. $designTypeComparison = [
  794. 'pk' => 'string',
  795. 'weigh' => 'number',
  796. 'timestamp' => 'datetime',
  797. 'float' => 'number',
  798. ];
  799. if (array_key_exists($field['designType'], $designTypeComparison)) {
  800. $field['designType'] = $designTypeComparison[$field['designType']];
  801. }
  802. // 是否开启了多选
  803. $supportMultipleComparison = ['select', 'image', 'file', 'remoteSelect'];
  804. if (in_array($field['designType'], $supportMultipleComparison)) {
  805. $multiKey = $field['designType'] == 'remoteSelect' ? 'select-multi' : $field['designType'] . '-multi';
  806. if (isset($field['form'][$multiKey]) && $field['form'][$multiKey]) {
  807. $field['designType'] = $field['designType'] . 's';
  808. }
  809. }
  810. }
  811. public static function getTableColumnsDataType($column)
  812. {
  813. if (stripos($column['COLUMN_NAME'], 'id') !== false && stripos($column['EXTRA'], 'auto_increment') !== false) {
  814. return 'pk';
  815. } elseif ($column['COLUMN_NAME'] == 'weigh') {
  816. return 'weigh';
  817. } elseif (in_array($column['COLUMN_NAME'], ['createtime', 'updatetime', 'create_time', 'update_time'])) {
  818. return 'timestamp';
  819. }
  820. foreach (self::$inputTypeRule as $item) {
  821. $typeBool = true;
  822. $suffixBool = true;
  823. $columnTypeBool = true;
  824. if (isset($item['type']) && $item['type'] && !in_array($column['DATA_TYPE'], $item['type'])) {
  825. $typeBool = false;
  826. }
  827. if (isset($item['suffix']) && $item['suffix']) {
  828. $suffixBool = self::isMatchSuffix($column['COLUMN_NAME'], $item['suffix']);
  829. }
  830. if (isset($item['column_type']) && $item['column_type'] && !in_array($column['COLUMN_TYPE'], $item['column_type'])) {
  831. $columnTypeBool = false;
  832. }
  833. if ($typeBool && $suffixBool && $columnTypeBool) {
  834. return $item['value'];
  835. }
  836. }
  837. return 'string';
  838. }
  839. /**
  840. * 判断是否符合指定后缀
  841. *
  842. * @param string $field 字段名称
  843. * @param string|array $suffixArr 后缀
  844. * @return bool
  845. */
  846. protected static function isMatchSuffix(string $field, string|array $suffixArr): bool
  847. {
  848. $suffixArr = is_array($suffixArr) ? $suffixArr : explode(',', $suffixArr);
  849. foreach ($suffixArr as $v) {
  850. if (preg_match("/$v$/i", $field)) {
  851. return true;
  852. }
  853. }
  854. return false;
  855. }
  856. /**
  857. * 创建菜单
  858. * @throws Throwable
  859. */
  860. public static function createMenu($webViewsDir, $tableComment): void
  861. {
  862. $menuName = self::getMenuName($webViewsDir);
  863. if (AdminRule::where('name', $menuName)->value('id')) {
  864. return;
  865. }
  866. // 组装权限节点数据
  867. $menuChildren = self::$menuChildren;
  868. foreach ($menuChildren as &$item) {
  869. $item['name'] = $menuName . $item['name'];
  870. }
  871. // 组件路径
  872. $componentPath = str_replace(['\\', 'web/src'], ['/', '/src'], $webViewsDir['views'] . '/' . 'index.vue');
  873. // 菜单数组
  874. $menus = [
  875. 'type' => 'menu',
  876. 'title' => $tableComment ?: $webViewsDir['originalLastName'],
  877. 'name' => $menuName,
  878. 'path' => $menuName,
  879. 'menu_type' => 'tab',
  880. 'keepalive' => 1,
  881. 'component' => $componentPath,
  882. 'children' => $menuChildren,
  883. ];
  884. $paths = array_reverse($webViewsDir['path']);
  885. foreach ($paths as $path) {
  886. $menus = [
  887. 'type' => 'menu_dir',
  888. 'title' => $path,
  889. 'name' => $path,
  890. 'path' => $path,
  891. 'children' => [$menus],
  892. ];
  893. }
  894. // 创建菜单
  895. Menu::create([$menus], 0, 'ignore');
  896. }
  897. public static function writeWebLangFile($langData, $webLangDir): void
  898. {
  899. foreach ($langData as $lang => $langDatum) {
  900. $langTsContent = '';
  901. foreach ($langDatum as $key => $item) {
  902. $quote = self::getQuote($item);
  903. $keyStr = self::formatObjectKey($key);
  904. $langTsContent .= self::tab() . $keyStr . ": $quote$item$quote,\n";
  905. }
  906. $langTsContent = "export default {\n" . $langTsContent . "}\n";
  907. self::writeFile(root_path() . $webLangDir[$lang] . '.ts', $langTsContent);
  908. }
  909. }
  910. public static function writeFile($path, $content): bool|int
  911. {
  912. $path = Filesystem::fsFit($path);
  913. if (!is_dir(dirname($path))) {
  914. mkdir(dirname($path), 0755, true);
  915. }
  916. return file_put_contents($path, $content);
  917. }
  918. public static function buildModelAppend($append): string
  919. {
  920. if (!$append) return '';
  921. $append = self::buildFormatSimpleArray($append);
  922. return "\n" . self::tab() . "// 追加属性" . "\n" . self::tab() . "protected \$append = $append;\n";
  923. }
  924. public static function buildModelFieldType(array $fieldType): string
  925. {
  926. if (!$fieldType) return '';
  927. $maxStrLang = 0;
  928. foreach ($fieldType as $key => $item) {
  929. $strLang = strlen($key);
  930. $maxStrLang = max($strLang, $maxStrLang);
  931. }
  932. $str = '';
  933. foreach ($fieldType as $key => $item) {
  934. $str .= self::tab(2) . "'$key'" . str_pad('=>', ($maxStrLang - strlen($key) + 3), ' ', STR_PAD_LEFT) . " '$item',\n";
  935. }
  936. return "\n" . self::tab() . "// 字段类型转换" . "\n" . self::tab() . "protected \$type = [\n" . rtrim($str, "\n") . "\n" . self::tab() . "];\n";
  937. }
  938. public static function writeModelFile(string $tablePk, array $fieldsMap, array $modelData, array $modelFile): void
  939. {
  940. if ($modelData['connection'] && $modelData['connection'] != config('database.default')) {
  941. $modelData['connection'] = "\n" . self::tab() . "// 数据库连接配置标识\n" . self::tab() . 'protected $connection = ' . "'{$modelData['connection']}';\n";
  942. } else {
  943. $modelData['connection'] = '';
  944. }
  945. $modelData['pk'] = $tablePk == 'id' ? '' : "\n" . self::tab() . "// 表主键\n" . self::tab() . 'protected $pk = ' . "'$tablePk';\n";
  946. $modelData['autoWriteTimestamp'] = array_key_exists(self::$createTimeField, $fieldsMap) || array_key_exists(self::$updateTimeField, $fieldsMap) ? 'true' : 'false';
  947. if ($modelData['autoWriteTimestamp'] == 'true') {
  948. $modelData['createTime'] = array_key_exists(self::$createTimeField, $fieldsMap) ? '' : "\n" . self::tab() . "protected \$createTime = false;";
  949. $modelData['updateTime'] = array_key_exists(self::$updateTimeField, $fieldsMap) ? '' : "\n" . self::tab() . "protected \$updateTime = false;";
  950. }
  951. $modelMethodList = isset($modelData['relationMethodList']) ? array_merge($modelData['methods'], $modelData['relationMethodList']) : $modelData['methods'];
  952. $modelData['methods'] = $modelMethodList ? "\n" . implode("\n", $modelMethodList) : '';
  953. $modelData['append'] = self::buildModelAppend($modelData['append']);
  954. $modelData['fieldType'] = self::buildModelFieldType($modelData['fieldType']);
  955. // 生成雪花ID?
  956. if (isset($modelData['beforeInsertMixins']['snowflake'])) {
  957. // beforeInsert 组装
  958. $modelData['beforeInsert'] = Helper::assembleStub('mixins/model/beforeInsert', [
  959. 'setSnowFlakeIdCode' => $modelData['beforeInsertMixins']['snowflake']
  960. ]);
  961. }
  962. if ($modelData['afterInsert'] && $modelData['beforeInsert']) {
  963. $modelData['afterInsert'] = "\n" . $modelData['afterInsert'];
  964. }
  965. $modelFileContent = self::assembleStub('mixins/model/model', $modelData);
  966. self::writeFile($modelFile['parseFile'], $modelFileContent);
  967. }
  968. public static function writeControllerFile(array $controllerData, array $controllerFile): void
  969. {
  970. if (isset($controllerData['relationVisibleFieldList']) && $controllerData['relationVisibleFieldList']) {
  971. $relationVisibleFields = '->visible([';
  972. foreach ($controllerData['relationVisibleFieldList'] as $cKey => $controllerDatum) {
  973. $relationVisibleFields .= "'$cKey' => ['" . implode("', '", $controllerDatum) . "'], ";
  974. }
  975. $relationVisibleFields = rtrim($relationVisibleFields, ', ');
  976. $relationVisibleFields .= '])';
  977. // 重写index
  978. $controllerData['methods']['index'] = self::assembleStub('mixins/controller/index', [
  979. 'relationVisibleFields' => $relationVisibleFields
  980. ]);
  981. $controllerData['use']['Throwable'] = "\nuse Throwable;";
  982. unset($controllerData['relationVisibleFieldList']);
  983. }
  984. $controllerAttr = '';
  985. foreach ($controllerData['attr'] as $key => $item) {
  986. $attrType = '';
  987. if (array_key_exists($key, self::$attrType['controller'])) {
  988. $attrType = self::$attrType['controller'][$key];
  989. }
  990. if (is_array($item)) {
  991. $controllerAttr .= "\n" . self::tab() . "protected $attrType \$$key = ['" . implode("', '", $item) . "'];\n";
  992. } elseif ($item) {
  993. $controllerAttr .= "\n" . self::tab() . "protected $attrType \$$key = '$item';\n";
  994. }
  995. }
  996. $controllerData['attr'] = $controllerAttr;
  997. $controllerData['initialize'] = self::assembleStub('mixins/controller/initialize', [
  998. 'modelNamespace' => $controllerData['modelNamespace'],
  999. 'modelName' => $controllerData['modelName'],
  1000. 'filterRule' => $controllerData['filterRule'],
  1001. ]);
  1002. $contentFileContent = self::assembleStub('mixins/controller/controller', $controllerData);
  1003. self::writeFile($controllerFile['parseFile'], $contentFileContent);
  1004. }
  1005. public static function writeFormFile($formVueData, $webViewsDir, $fields, $webTranslate): void
  1006. {
  1007. $fieldHtml = "\n";
  1008. $formVueData['bigDialog'] = $formVueData['bigDialog'] ? "\n" . self::tab(2) . 'width="70%"' : '';
  1009. foreach ($formVueData['formFields'] as $field) {
  1010. $fieldHtml .= self::tab(5) . "<FormItem";
  1011. foreach ($field as $key => $attr) {
  1012. if (is_array($attr)) {
  1013. $fieldHtml .= ' ' . $key . '="' . self::getJsonFromArray($attr) . '"';
  1014. } else {
  1015. $fieldHtml .= ' ' . $key . '="' . $attr . '"';
  1016. }
  1017. }
  1018. $fieldHtml .= " />\n";
  1019. }
  1020. $formVueData['formFields'] = rtrim($fieldHtml, "\n");
  1021. // 表单验证规则
  1022. foreach ($fields as $field) {
  1023. if (isset($field['form']['validator'])) {
  1024. foreach ($field['form']['validator'] as $item) {
  1025. $message = '';
  1026. if (isset($field['form']['validatorMsg']) && $field['form']['validatorMsg']) {
  1027. $message = ", message: '{$field['form']['validatorMsg']}'";
  1028. }
  1029. $formVueData['formValidatorRules'][$field['name']][] = "buildValidatorData({ name: '$item', title: t('$webTranslate{$field['name']}')$message })";
  1030. }
  1031. }
  1032. }
  1033. if ($formVueData['formValidatorRules']) {
  1034. $formVueData['imports'][] = "import { buildValidatorData } from '/@/utils/validate'";
  1035. }
  1036. $formVueData['importExpand'] = self::buildImportExpand($formVueData['imports']);
  1037. $formVueData['formItemRules'] = self::buildFormValidatorRules($formVueData['formValidatorRules']);
  1038. $formVueContent = self::assembleStub('html/form', $formVueData);
  1039. self::writeFile(root_path() . $webViewsDir['views'] . '/' . 'popupForm.vue', $formVueContent);
  1040. }
  1041. public static function buildImportExpand(array $imports): string
  1042. {
  1043. $importExpand = '';
  1044. foreach ($imports as $import) {
  1045. $importExpand .= "\n$import";
  1046. }
  1047. return $importExpand;
  1048. }
  1049. public static function buildFormValidatorRules(array $formValidatorRules): string
  1050. {
  1051. $rulesHtml = "";
  1052. foreach ($formValidatorRules as $key => $formItemRule) {
  1053. $rulesArrHtml = '';
  1054. foreach ($formItemRule as $item) {
  1055. $rulesArrHtml .= $item . ', ';
  1056. }
  1057. $rulesHtml .= self::tab() . $key . ': [' . rtrim($rulesArrHtml, ', ') . "],\n";
  1058. }
  1059. return $rulesHtml ? "\n" . $rulesHtml : '';
  1060. }
  1061. public static function writeIndexFile($indexVueData, $webViewsDir, $controllerFile): void
  1062. {
  1063. $indexVueData['optButtons'] = self::buildSimpleArray($indexVueData['optButtons']);
  1064. $indexVueData['defaultItems'] = self::getJsonFromArray($indexVueData['defaultItems']);
  1065. $indexVueData['tableColumn'] = self::buildTableColumn($indexVueData['tableColumn']);
  1066. $indexVueData['dblClickNotEditColumn'] = self::buildSimpleArray($indexVueData['dblClickNotEditColumn']);
  1067. $controllerFile['path'][] = $controllerFile['originalLastName'];
  1068. $indexVueData['controllerUrl'] = '\'/admin/' . ($controllerFile['path'] ? implode('.', $controllerFile['path']) : '') . '/\'';
  1069. $indexVueData['componentName'] = ($webViewsDir['path'] ? implode('/', $webViewsDir['path']) . '/' : '') . $webViewsDir['originalLastName'];
  1070. $indexVueContent = self::assembleStub('html/index', $indexVueData);
  1071. self::writeFile(root_path() . $webViewsDir['views'] . '/' . 'index.vue', $indexVueContent);
  1072. }
  1073. public static function buildTableColumn($tableColumnList): string
  1074. {
  1075. $columnJson = '';
  1076. foreach ($tableColumnList as $column) {
  1077. $columnJson .= self::tab(3) . '{';
  1078. foreach ($column as $key => $item) {
  1079. $columnJson .= self::buildTableColumnKey($key, $item);
  1080. }
  1081. $columnJson = rtrim($columnJson, ',');
  1082. $columnJson .= ' }' . ",\n";
  1083. }
  1084. return rtrim($columnJson, "\n");
  1085. }
  1086. public static function buildTableColumnKey($key, $item): string
  1087. {
  1088. $key = self::formatObjectKey($key);
  1089. if (is_array($item)) {
  1090. $itemJson = ' ' . $key . ': {';
  1091. foreach ($item as $ik => $iItem) {
  1092. $itemJson .= self::buildTableColumnKey($ik, $iItem);
  1093. }
  1094. $itemJson = rtrim($itemJson, ',');
  1095. $itemJson .= ' }';
  1096. } elseif ($item === 'false' || $item === 'true') {
  1097. $itemJson = ' ' . $key . ': ' . $item . ',';
  1098. } elseif (in_array($key, ['label', 'width', 'buttons'], true) || str_starts_with($item, "t('") || str_starts_with($item, "t(\"")) {
  1099. $itemJson = ' ' . $key . ': ' . $item . ',';
  1100. } else {
  1101. $itemJson = ' ' . $key . ': \'' . $item . '\',';
  1102. }
  1103. return $itemJson;
  1104. }
  1105. public static function formatObjectKey(string $keyName): string
  1106. {
  1107. if (preg_match("/^[a-zA-Z_][a-zA-Z0-9_]+$/", $keyName)) {
  1108. return $keyName;
  1109. } else {
  1110. $quote = self::getQuote($keyName);
  1111. return "$quote$keyName$quote";
  1112. }
  1113. }
  1114. public static function getQuote(string $value): string
  1115. {
  1116. return stripos($value, "'") === false ? "'" : '"';
  1117. }
  1118. public static function buildFormatSimpleArray($arr, int $tab = 2): string
  1119. {
  1120. if (!$arr) return '[]';
  1121. $str = '[' . PHP_EOL;
  1122. foreach ($arr as $item) {
  1123. if ($item == 'undefined' || $item == 'false' || is_numeric($item)) {
  1124. $str .= self::tab($tab) . $item . ',' . PHP_EOL;
  1125. } else {
  1126. $quote = self::getQuote($item);
  1127. $str .= self::tab($tab) . "$quote$item$quote," . PHP_EOL;
  1128. }
  1129. }
  1130. return $str . self::tab($tab - 1) . ']';
  1131. }
  1132. public static function buildSimpleArray($arr): string
  1133. {
  1134. if (!$arr) return '[]';
  1135. $str = '';
  1136. foreach ($arr as $item) {
  1137. if ($item == 'undefined' || $item == 'false' || is_numeric($item)) {
  1138. $str .= $item . ', ';
  1139. } else {
  1140. $quote = self::getQuote($item);
  1141. $str .= "$quote$item$quote, ";
  1142. }
  1143. }
  1144. return '[' . rtrim($str, ", ") . ']';
  1145. }
  1146. public static function buildDefaultOrder(string $field, string $type): string
  1147. {
  1148. if ($field && $type) {
  1149. $defaultOrderStub = [
  1150. 'prop' => $field,
  1151. 'order' => $type,
  1152. ];
  1153. $defaultOrderStub = self::getJsonFromArray($defaultOrderStub);
  1154. if ($defaultOrderStub) {
  1155. return "\n" . self::tab(2) . "defaultOrder: " . $defaultOrderStub . ',';
  1156. }
  1157. }
  1158. return '';
  1159. }
  1160. public static function getJsonFromArray($arr)
  1161. {
  1162. if (is_array($arr)) {
  1163. $jsonStr = '';
  1164. foreach ($arr as $key => $item) {
  1165. $keyStr = ' ' . self::formatObjectKey($key) . ': ';
  1166. if (is_array($item)) {
  1167. $jsonStr .= $keyStr . self::getJsonFromArray($item) . ',';
  1168. } elseif ($item === 'false' || $item === 'true') {
  1169. $jsonStr .= $keyStr . ($item === 'false' ? 'false' : 'true') . ',';
  1170. } elseif ($item === null) {
  1171. $jsonStr .= $keyStr . 'null,';
  1172. } elseif (str_starts_with($item, "t('") || str_starts_with($item, "t(\"") || $item == '[]' || in_array(gettype($item), ['integer', 'double'])) {
  1173. $jsonStr .= $keyStr . $item . ',';
  1174. } elseif (isset($item[0]) && $item[0] == '[' && str_ends_with($item, ']')) {
  1175. $jsonStr .= $keyStr . $item . ',';
  1176. } else {
  1177. $quote = self::getQuote($item);
  1178. $jsonStr .= $keyStr . "$quote$item$quote,";
  1179. }
  1180. }
  1181. return $jsonStr ? '{' . rtrim($jsonStr, ',') . ' }' : '{}';
  1182. } else {
  1183. return $arr;
  1184. }
  1185. }
  1186. }