Helper.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  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. ],
  231. ];
  232. /**
  233. * 获取字段字典数据
  234. * @param array $dict 存储字典数据的变量
  235. * @param array $field 字段数据
  236. * @param string $lang 语言
  237. * @param string $translationPrefix 翻译前缀
  238. */
  239. public static function getDictData(array &$dict, array $field, string $lang, string $translationPrefix = ''): array
  240. {
  241. if (!$field['comment']) return [];
  242. $comment = str_replace([',', ':'], [',', ':'], $field['comment']);
  243. if (stripos($comment, ':') !== false && stripos($comment, ',') && stripos($comment, '=') !== false) {
  244. [$fieldTitle, $item] = explode(':', $comment);
  245. $dict[$translationPrefix . $field['name']] = $lang == 'en' ? $field['name'] : $fieldTitle;
  246. foreach (explode(',', $item) as $v) {
  247. $valArr = explode('=', $v);
  248. if (count($valArr) == 2) {
  249. [$key, $value] = $valArr;
  250. $dict[$translationPrefix . $field['name'] . ' ' . $key] = $lang == 'en' ? $field['name'] . ' ' . $key : $value;
  251. }
  252. }
  253. } else {
  254. $dict[$translationPrefix . $field['name']] = $lang == 'en' ? $field['name'] : $comment;
  255. }
  256. return $dict;
  257. }
  258. /**
  259. * 记录CRUD状态
  260. * @param array $data CRUD记录数据
  261. * @return int 记录ID
  262. */
  263. public static function recordCrudStatus(array $data): int
  264. {
  265. if (isset($data['id'])) {
  266. CrudLog::where('id', $data['id'])
  267. ->update([
  268. 'status' => $data['status'],
  269. ]);
  270. return $data['id'];
  271. }
  272. $connection = $data['table']['databaseConnection'] ?: config('database.default');
  273. $log = CrudLog::create([
  274. 'table_name' => $data['table']['name'],
  275. 'table' => $data['table'],
  276. 'fields' => $data['fields'],
  277. 'connection' => $connection,
  278. 'status' => $data['status'],
  279. ]);
  280. return $log->id;
  281. }
  282. /**
  283. * 获取 Phinx 的字段类型数据
  284. * @param string $type 字段类型
  285. * @param array $field 字段数据
  286. * @return array
  287. */
  288. public static function getPhinxFieldType(string $type, array $field): array
  289. {
  290. if ($type == 'tinyint') {
  291. if ((isset($field['dataType']) && $field['dataType'] == 'tinyint(1)') || $field['default'] == '1') {
  292. $type = 'boolean';
  293. }
  294. }
  295. $phinxFieldTypeMap = [
  296. // 数字
  297. 'tinyint' => ['type' => AdapterInterface::PHINX_TYPE_INTEGER, 'limit' => MysqlAdapter::INT_TINY],
  298. 'smallint' => ['type' => AdapterInterface::PHINX_TYPE_INTEGER, 'limit' => MysqlAdapter::INT_SMALL],
  299. 'mediumint' => ['type' => AdapterInterface::PHINX_TYPE_INTEGER, 'limit' => MysqlAdapter::INT_MEDIUM],
  300. 'int' => ['type' => AdapterInterface::PHINX_TYPE_INTEGER, 'limit' => null],
  301. 'bigint' => ['type' => AdapterInterface::PHINX_TYPE_BIG_INTEGER, 'limit' => null],
  302. 'boolean' => ['type' => AdapterInterface::PHINX_TYPE_BOOLEAN, 'limit' => null],
  303. // 文本
  304. 'varchar' => ['type' => AdapterInterface::PHINX_TYPE_STRING, 'limit' => null],
  305. 'tinytext' => ['type' => AdapterInterface::PHINX_TYPE_TEXT, 'limit' => MysqlAdapter::TEXT_TINY],
  306. 'mediumtext' => ['type' => AdapterInterface::PHINX_TYPE_TEXT, 'limit' => MysqlAdapter::TEXT_MEDIUM],
  307. 'longtext' => ['type' => AdapterInterface::PHINX_TYPE_TEXT, 'limit' => MysqlAdapter::TEXT_LONG],
  308. 'tinyblob' => ['type' => AdapterInterface::PHINX_TYPE_BLOB, 'limit' => MysqlAdapter::BLOB_TINY],
  309. 'mediumblob' => ['type' => AdapterInterface::PHINX_TYPE_BLOB, 'limit' => MysqlAdapter::BLOB_MEDIUM],
  310. 'longblob' => ['type' => AdapterInterface::PHINX_TYPE_BLOB, 'limit' => MysqlAdapter::BLOB_LONG],
  311. ];
  312. return array_key_exists($type, $phinxFieldTypeMap) ? $phinxFieldTypeMap[$type] : ['type' => $type, 'limit' => null];
  313. }
  314. /**
  315. * 分析字段limit和精度
  316. * @param string $type 字段类型
  317. * @param array $field 字段数据
  318. * @return array ['limit' => 10, 'precision' => null, 'scale' => null]
  319. */
  320. public static function analyseFieldLimit(string $type, array $field): array
  321. {
  322. $fieldType = [
  323. 'decimal' => ['decimal', 'double', 'float'],
  324. 'values' => ['enum', 'set'],
  325. ];
  326. $dataTypeLimit = self::dataTypeLimit($field['dataType'] ?? '');
  327. if (in_array($type, $fieldType['decimal'])) {
  328. if ($dataTypeLimit) {
  329. return ['precision' => $dataTypeLimit[0], 'scale' => $dataTypeLimit[1] ?? 0];
  330. }
  331. $scale = isset($field['precision']) ? intval($field['precision']) : 0;
  332. return ['precision' => $field['length'] ?: 10, 'scale' => $scale];
  333. } elseif (in_array($type, $fieldType['values'])) {
  334. foreach ($dataTypeLimit as &$item) {
  335. $item = str_replace(['"', "'"], '', $item);
  336. }
  337. return ['values' => $dataTypeLimit];
  338. } elseif ($dataTypeLimit && $dataTypeLimit[0]) {
  339. return ['limit' => $dataTypeLimit[0]];
  340. } elseif (isset($field['length'])) {
  341. return ['limit' => $field['length']];
  342. }
  343. return [];
  344. }
  345. public static function dataTypeLimit(string $dataType): array
  346. {
  347. preg_match("/\((.*?)\)/", $dataType, $matches);
  348. if (isset($matches[1]) && $matches[1]) {
  349. return explode(',', trim($matches[1], ','));
  350. }
  351. return [];
  352. }
  353. public static function analyseFieldDefault(array $field): mixed
  354. {
  355. if (strtolower((string)$field['default']) == 'null') {
  356. return null;
  357. }
  358. return match ($field['default']) {
  359. 'empty string' => '',
  360. default => $field['default'],
  361. };
  362. }
  363. public static function searchArray($fields, callable $myFunction): array|bool
  364. {
  365. foreach ($fields as $key => $field) {
  366. if (call_user_func($myFunction, $field, $key)) {
  367. return $field;
  368. }
  369. }
  370. return false;
  371. }
  372. /**
  373. * 获取 Phinx 格式的字段数据
  374. * @param array $field
  375. * @return array
  376. */
  377. public static function getPhinxFieldData(array $field): array
  378. {
  379. $conciseType = self::analyseFieldType($field);
  380. $phinxTypeData = self::getPhinxFieldType($conciseType, $field);
  381. $phinxColumnOptions = self::analyseFieldLimit($conciseType, $field);
  382. if (!is_null($phinxTypeData['limit'])) {
  383. $phinxColumnOptions['limit'] = $phinxTypeData['limit'];
  384. }
  385. // 无默认值字段
  386. $noDefaultValueFields = [
  387. 'text', 'blob', 'geometry', 'geometrycollection', 'json', 'linestring', 'longblob', 'longtext', 'mediumblob',
  388. 'mediumtext', 'multilinestring', 'multipoint', 'multipolygon', 'point', 'polygon', 'tinyblob',
  389. ];
  390. if ($field['default'] != 'none' && !in_array($conciseType, $noDefaultValueFields)) {
  391. $phinxColumnOptions['default'] = self::analyseFieldDefault($field);
  392. }
  393. $phinxColumnOptions['null'] = (bool)$field['null'];
  394. $phinxColumnOptions['comment'] = $field['comment'];
  395. $phinxColumnOptions['signed'] = !$field['unsigned'];
  396. $phinxColumnOptions['identity'] = $field['autoIncrement'];
  397. return [
  398. 'type' => $phinxTypeData['type'],
  399. 'options' => $phinxColumnOptions,
  400. ];
  401. }
  402. /**
  403. * 表字段排序
  404. * @param string $tableName 表名
  405. * @param array $fields 字段数据
  406. * @param array $designChange 前端字段改变数据
  407. * @param ?string $connection 数据库连接标识
  408. * @return void
  409. * @throws Throwable
  410. */
  411. public static function updateFieldOrder(string $tableName, array $fields, array $designChange, ?string $connection = null): void
  412. {
  413. if ($designChange) {
  414. $table = TableManager::phinxTable($tableName, [], false, $connection);
  415. foreach ($designChange as $item) {
  416. if (!$item['sync']) continue;
  417. if (!empty($item['after'])) {
  418. $fieldName = in_array($item['type'], ['add-field', 'change-field-name']) ? $item['newName'] : $item['oldName'];
  419. $field = self::searchArray($fields, function ($field) use ($fieldName) {
  420. return $field['name'] == $fieldName;
  421. });
  422. $phinxFieldData = self::getPhinxFieldData($field);
  423. // 字段顺序调整
  424. if ($item['after'] == 'FIRST FIELD') {
  425. $phinxFieldData['options']['after'] = MysqlAdapter::FIRST;
  426. } else {
  427. $phinxFieldData['options']['after'] = $item['after'];
  428. }
  429. $table->changeColumn($fieldName, $phinxFieldData['type'], $phinxFieldData['options']);
  430. }
  431. }
  432. $table->update();
  433. }
  434. }
  435. /**
  436. * 表设计处理
  437. * @param array $table 表数据
  438. * @param array $fields 字段数据
  439. * @return array
  440. * @throws Throwable
  441. */
  442. public static function handleTableDesign(array $table, array $fields): array
  443. {
  444. $name = TableManager::tableName($table['name'], true, $table['databaseConnection']);
  445. $comment = $table['comment'] ?? '';
  446. $designChange = $table['designChange'] ?? [];
  447. $adapter = TableManager::phinxAdapter(false, $table['databaseConnection']);
  448. $pk = self::searchArray($fields, function ($item) {
  449. return $item['primaryKey'];
  450. });
  451. $pk = $pk ? $pk['name'] : '';
  452. if ($adapter->hasTable($name)) {
  453. // 更新表
  454. if ($designChange) {
  455. $tableManager = TableManager::phinxTable($name, [], false, $table['databaseConnection']);
  456. $tableManager->changeComment($comment)->update();
  457. // 改名和删除操作优先
  458. $priorityOpt = false;
  459. foreach ($designChange as $item) {
  460. if (!$item['sync']) continue;
  461. if (in_array($item['type'], ['change-field-name', 'del-field']) && !$tableManager->hasColumn($item['oldName'])) {
  462. // 字段不存在
  463. throw new BaException(__($item['type'] . ' fail not exist', [$item['oldName']]));
  464. }
  465. if ($item['type'] == 'change-field-name') {
  466. $priorityOpt = true;
  467. $tableManager->renameColumn($item['oldName'], $item['newName']);
  468. } elseif ($item['type'] == 'del-field') {
  469. $priorityOpt = true;
  470. $tableManager->removeColumn($item['oldName']);
  471. }
  472. }
  473. // 保存需要优先执行的操作,避免先改名再改属性时找不到字段
  474. if ($priorityOpt) {
  475. $tableManager->update();
  476. }
  477. // 修改字段属性和添加字段操作
  478. foreach ($designChange as $item) {
  479. if (!$item['sync']) continue;
  480. if ($item['type'] == 'change-field-attr') {
  481. if (!$tableManager->hasColumn($item['oldName'])) {
  482. // 字段不存在
  483. throw new BaException(__($item['type'] . ' fail not exist', [$item['oldName']]));
  484. }
  485. $phinxFieldData = self::getPhinxFieldData(self::searchArray($fields, function ($field) use ($item) {
  486. return $field['name'] == $item['oldName'];
  487. }));
  488. $tableManager->changeColumn($item['oldName'], $phinxFieldData['type'], $phinxFieldData['options']);
  489. } elseif ($item['type'] == 'add-field') {
  490. if ($tableManager->hasColumn($item['newName'])) {
  491. // 字段已经存在
  492. throw new BaException(__($item['type'] . ' fail exist', [$item['newName']]));
  493. }
  494. $phinxFieldData = self::getPhinxFieldData(self::searchArray($fields, function ($field) use ($item) {
  495. return $field['name'] == $item['newName'];
  496. }));
  497. $tableManager->addColumn($item['newName'], $phinxFieldData['type'], $phinxFieldData['options']);
  498. }
  499. }
  500. $tableManager->update();
  501. // 表更新结构完成再处理字段排序
  502. self::updateFieldOrder($name, $fields, $designChange, $table['databaseConnection']);
  503. }
  504. } else {
  505. // 创建表
  506. $tableManager = TableManager::phinxTable($name, [
  507. 'id' => false,
  508. 'comment' => $comment,
  509. 'row_format' => 'DYNAMIC',
  510. 'primary_key' => $pk,
  511. 'collation' => 'utf8mb4_unicode_ci',
  512. ], false, $table['databaseConnection']);
  513. foreach ($fields as $field) {
  514. $phinxFieldData = self::getPhinxFieldData($field);
  515. $tableManager->addColumn($field['name'], $phinxFieldData['type'], $phinxFieldData['options']);
  516. }
  517. $tableManager->create();
  518. }
  519. return [$pk];
  520. }
  521. /**
  522. * 解析文件数据
  523. * @throws Throwable
  524. */
  525. public static function parseNameData($app, $table, $type, $value = ''): array
  526. {
  527. $pathArr = [];
  528. if ($value) {
  529. $value = str_replace('.php', '', $value);
  530. $value = str_replace(['.', '/', '\\', '_'], '/', $value);
  531. $pathArrTemp = explode('/', $value);
  532. $redundantDir = [
  533. 'app' => 0,
  534. $app => 1,
  535. $type => 2,
  536. ];
  537. foreach ($pathArrTemp as $key => $item) {
  538. if (!array_key_exists($item, $redundantDir) || $key !== $redundantDir[$item]) {
  539. $pathArr[] = $item;
  540. }
  541. }
  542. } elseif (isset(self::$parseNamePresets[$type]) && array_key_exists($table, self::$parseNamePresets[$type])) {
  543. $pathArr = self::$parseNamePresets[$type][$table];
  544. } else {
  545. $table = str_replace(['.', '/', '\\', '_'], '/', $table);
  546. $pathArr = explode('/', $table);
  547. }
  548. $originalLastName = array_pop($pathArr);
  549. $pathArr = array_map('strtolower', $pathArr);
  550. $lastName = ucfirst($originalLastName);
  551. // 类名不能为内部关键字
  552. if (in_array(strtolower($originalLastName), self::$reservedKeywords)) {
  553. throw new Exception('Unable to use internal variable:' . $lastName);
  554. }
  555. $appDir = app()->getBasePath() . $app . DIRECTORY_SEPARATOR;
  556. $namespace = "app\\$app\\$type" . ($pathArr ? '\\' . implode('\\', $pathArr) : '');
  557. $parseFile = $appDir . $type . DIRECTORY_SEPARATOR . ($pathArr ? implode(DIRECTORY_SEPARATOR, $pathArr) . DIRECTORY_SEPARATOR : '') . $lastName . '.php';
  558. $rootFileName = $namespace . "/$lastName" . '.php';
  559. return [
  560. 'lastName' => $lastName,
  561. 'originalLastName' => $originalLastName,
  562. 'path' => $pathArr,
  563. 'namespace' => $namespace,
  564. 'parseFile' => Filesystem::fsFit($parseFile),
  565. 'rootFileName' => Filesystem::fsFit($rootFileName),
  566. ];
  567. }
  568. public static function parseWebDirNameData($table, $type, $value = ''): array
  569. {
  570. $pathArr = [];
  571. if ($value) {
  572. $value = str_replace(['.', '/', '\\', '_'], '/', $value);
  573. $pathArrTemp = explode('/', $value);
  574. $redundantDir = [
  575. 'web' => 0,
  576. 'src' => 1,
  577. 'views' => 2,
  578. 'lang' => 2,
  579. 'backend' => 3,
  580. 'pages' => 3,
  581. 'en' => 4,
  582. 'zh-cn' => 4,
  583. ];
  584. foreach ($pathArrTemp as $key => $item) {
  585. if (!array_key_exists($item, $redundantDir) || $key !== $redundantDir[$item]) {
  586. $pathArr[] = $item;
  587. }
  588. }
  589. } elseif (array_key_exists($table, self::$parseWebDirPresets[$type])) {
  590. $pathArr = self::$parseWebDirPresets[$type][$table];
  591. } else {
  592. $table = str_replace(['.', '/', '\\', '_'], '/', $table);
  593. $pathArr = explode('/', $table);
  594. }
  595. $originalLastName = array_pop($pathArr);
  596. $pathArr = array_map('strtolower', $pathArr);
  597. $lastName = lcfirst($originalLastName);
  598. $webDir['path'] = $pathArr;
  599. $webDir['lastName'] = $lastName;
  600. $webDir['originalLastName'] = $originalLastName;
  601. if ($type == 'views') {
  602. $webDir['views'] = "web/src/views/backend" . ($pathArr ? '/' . implode('/', $pathArr) : '') . "/$lastName";
  603. } elseif ($type == 'lang') {
  604. $webDir['lang'] = array_merge($pathArr, [$lastName]);
  605. $langDir = ['en', 'zh-cn'];
  606. foreach ($langDir as $item) {
  607. $webDir[$item] = "web/src/lang/backend/$item" . ($pathArr ? '/' . implode('/', $pathArr) : '') . "/$lastName";
  608. }
  609. }
  610. foreach ($webDir as &$item) {
  611. if (is_string($item)) $item = Filesystem::fsFit($item);
  612. }
  613. return $webDir;
  614. }
  615. /**
  616. * 获取菜单name、path
  617. * @param array $webDir
  618. * @return string
  619. */
  620. public static function getMenuName(array $webDir): string
  621. {
  622. return ($webDir['path'] ? implode('/', $webDir['path']) . '/' : '') . $webDir['originalLastName'];
  623. }
  624. /**
  625. * 获取基础模板文件路径
  626. * @param string $name
  627. * @return string
  628. */
  629. public static function getStubFilePath(string $name): string
  630. {
  631. return app_path() . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'crud' . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR . Filesystem::fsFit($name) . '.stub';
  632. }
  633. /**
  634. * 组装模板
  635. * @param string $name
  636. * @param array $data
  637. * @param bool $escape
  638. * @return string
  639. */
  640. public static function assembleStub(string $name, array $data, bool $escape = false): string
  641. {
  642. foreach ($data as &$datum) {
  643. $datum = is_array($datum) ? implode(PHP_EOL, $datum) : $datum;
  644. }
  645. $search = $replace = [];
  646. foreach ($data as $k => $v) {
  647. $search[] = "{%$k%}";
  648. $replace[] = $v;
  649. }
  650. $stubPath = self::getStubFilePath($name);
  651. $stubContent = file_get_contents($stubPath);
  652. $content = str_replace($search, $replace, $stubContent);
  653. return $escape ? self::escape($content) : $content;
  654. }
  655. /**
  656. * 获取转义编码后的值
  657. * @param array|string $value
  658. * @return string
  659. */
  660. public static function escape(array|string $value): string
  661. {
  662. if (is_array($value)) {
  663. $value = json_encode($value, JSON_UNESCAPED_UNICODE);
  664. }
  665. return htmlspecialchars($value, ENT_QUOTES, 'UTF-8', false);
  666. }
  667. public static function tab(int $num = 1): string
  668. {
  669. return str_pad('', 4 * $num);
  670. }
  671. /**
  672. * 根据数据表解析字段数据
  673. * @throws Throwable
  674. */
  675. public static function parseTableColumns(string $table, bool $analyseField = false, ?string $connection = null): array
  676. {
  677. $connection = TableManager::getConnection($connection);
  678. $connectionConfig = TableManager::getConnectionConfig($connection);
  679. // 从数据库中获取表字段信息
  680. $sql = 'SELECT * FROM `information_schema`.`columns` '
  681. . 'WHERE TABLE_SCHEMA = ? AND table_name = ? '
  682. . 'ORDER BY ORDINAL_POSITION';
  683. $columns = [];
  684. $tableColumn = Db::connect($connection)->query($sql, [$connectionConfig['database'], TableManager::tableName($table, true, $connection)]);
  685. foreach ($tableColumn as $item) {
  686. $isNullAble = $item['IS_NULLABLE'] == 'YES';
  687. if (str_contains($item['COLUMN_TYPE'], '(')) {
  688. $dataType = substr_replace($item['COLUMN_TYPE'], '', stripos($item['COLUMN_TYPE'], ')') + 1);
  689. } else {
  690. $dataType = str_replace(' unsigned', '', $item['COLUMN_TYPE']);
  691. }
  692. $column = [
  693. 'name' => $item['COLUMN_NAME'],
  694. 'type' => $item['DATA_TYPE'],
  695. 'dataType' => $dataType,
  696. 'default' => ($isNullAble && is_null($item['COLUMN_DEFAULT'])) ? 'null' : $item['COLUMN_DEFAULT'],
  697. 'null' => $isNullAble,
  698. 'primaryKey' => $item['COLUMN_KEY'] == 'PRI',
  699. 'unsigned' => (bool)stripos($item['COLUMN_TYPE'], 'unsigned'),
  700. 'autoIncrement' => stripos($item['EXTRA'], 'auto_increment') !== false,
  701. 'comment' => $item['COLUMN_COMMENT'],
  702. 'designType' => self::getTableColumnsDataType($item),
  703. 'table' => [],
  704. 'form' => [],
  705. ];
  706. if ($analyseField) {
  707. self::analyseField($column);
  708. } else {
  709. self::handleTableColumn($column);
  710. }
  711. $columns[$item['COLUMN_NAME']] = $column;
  712. }
  713. return $columns;
  714. }
  715. /**
  716. * 解析到的表字段的额外处理
  717. */
  718. public static function handleTableColumn(&$column): void
  719. {
  720. // 预留
  721. }
  722. /**
  723. * 分析字段数据类型
  724. * @param array $field 字段数据
  725. * @return string 字段类型
  726. */
  727. public static function analyseFieldType(array $field): string
  728. {
  729. $dataType = (isset($field['dataType']) && $field['dataType']) ? $field['dataType'] : $field['type'];
  730. if (stripos($dataType, '(') !== false) {
  731. $typeName = explode('(', $dataType);
  732. return trim($typeName[0]);
  733. }
  734. return trim($dataType);
  735. }
  736. /**
  737. * 分析字段的完整数据类型定义
  738. * @param array $field 字段数据
  739. * @return string
  740. */
  741. public static function analyseFieldDataType(array $field): string
  742. {
  743. if (!empty($field['dataType'])) return $field['dataType'];
  744. $conciseType = self::analyseFieldType($field);
  745. $limit = self::analyseFieldLimit($conciseType, $field);
  746. if (isset($limit['precision'])) {
  747. $dataType = "$conciseType({$limit['precision']}, {$limit['scale']})";
  748. } elseif (isset($limit['values'])) {
  749. $values = implode(',', $limit['values']);
  750. $dataType = "$conciseType($values)";
  751. } else {
  752. $dataType = "$conciseType({$limit['limit']})";
  753. }
  754. return $dataType;
  755. }
  756. /**
  757. * 分析字段
  758. */
  759. public static function analyseField(&$field): void
  760. {
  761. $field['type'] = self::analyseFieldType($field);
  762. $field['originalDesignType'] = $field['designType'];
  763. // 表单项类型转换对照表
  764. $designTypeComparison = [
  765. 'pk' => 'string',
  766. 'weigh' => 'number',
  767. 'timestamp' => 'datetime',
  768. 'float' => 'number',
  769. ];
  770. if (array_key_exists($field['designType'], $designTypeComparison)) {
  771. $field['designType'] = $designTypeComparison[$field['designType']];
  772. }
  773. // 是否开启了多选
  774. $supportMultipleComparison = ['select', 'image', 'file', 'remoteSelect'];
  775. if (in_array($field['designType'], $supportMultipleComparison)) {
  776. $multiKey = $field['designType'] == 'remoteSelect' ? 'select-multi' : $field['designType'] . '-multi';
  777. if (isset($field['form'][$multiKey]) && $field['form'][$multiKey]) {
  778. $field['designType'] = $field['designType'] . 's';
  779. }
  780. }
  781. }
  782. public static function getTableColumnsDataType($column)
  783. {
  784. if (stripos($column['COLUMN_NAME'], 'id') !== false && stripos($column['EXTRA'], 'auto_increment') !== false) {
  785. return 'pk';
  786. } elseif ($column['COLUMN_NAME'] == 'weigh') {
  787. return 'weigh';
  788. } elseif (in_array($column['COLUMN_NAME'], ['createtime', 'updatetime', 'create_time', 'update_time'])) {
  789. return 'timestamp';
  790. }
  791. foreach (self::$inputTypeRule as $item) {
  792. $typeBool = true;
  793. $suffixBool = true;
  794. $columnTypeBool = true;
  795. if (isset($item['type']) && $item['type'] && !in_array($column['DATA_TYPE'], $item['type'])) {
  796. $typeBool = false;
  797. }
  798. if (isset($item['suffix']) && $item['suffix']) {
  799. $suffixBool = self::isMatchSuffix($column['COLUMN_NAME'], $item['suffix']);
  800. }
  801. if (isset($item['column_type']) && $item['column_type'] && !in_array($column['COLUMN_TYPE'], $item['column_type'])) {
  802. $columnTypeBool = false;
  803. }
  804. if ($typeBool && $suffixBool && $columnTypeBool) {
  805. return $item['value'];
  806. }
  807. }
  808. return 'string';
  809. }
  810. /**
  811. * 判断是否符合指定后缀
  812. *
  813. * @param string $field 字段名称
  814. * @param string|array $suffixArr 后缀
  815. * @return bool
  816. */
  817. protected static function isMatchSuffix(string $field, string|array $suffixArr): bool
  818. {
  819. $suffixArr = is_array($suffixArr) ? $suffixArr : explode(',', $suffixArr);
  820. foreach ($suffixArr as $v) {
  821. if (preg_match("/$v$/i", $field)) {
  822. return true;
  823. }
  824. }
  825. return false;
  826. }
  827. /**
  828. * 创建菜单
  829. * @throws Throwable
  830. */
  831. public static function createMenu($webViewsDir, $tableComment): void
  832. {
  833. $menuName = self::getMenuName($webViewsDir);
  834. if (!AdminRule::where('name', $menuName)->value('id')) {
  835. $pid = 0;
  836. foreach ($webViewsDir['path'] as $item) {
  837. $pMenu = AdminRule::where('name', $item)->value('id');
  838. if ($pMenu) {
  839. $pid = $pMenu;
  840. continue;
  841. }
  842. $menu = [
  843. 'pid' => $pid,
  844. 'type' => 'menu_dir',
  845. 'title' => $item,
  846. 'name' => $item,
  847. 'path' => $item,
  848. ];
  849. $menu = AdminRule::create($menu);
  850. $pid = $menu->id;
  851. }
  852. // 建立菜单
  853. foreach (self::$menuChildren as &$item) {
  854. $item['name'] = $menuName . $item['name'];
  855. }
  856. $componentPath = str_replace(['\\', 'web/src'], ['/', '/src'], $webViewsDir['views'] . '/' . 'index.vue');
  857. Menu::create([
  858. [
  859. 'type' => 'menu',
  860. 'title' => $tableComment ?: $webViewsDir['originalLastName'],
  861. 'name' => $menuName,
  862. 'path' => $menuName,
  863. 'menu_type' => 'tab',
  864. 'keepalive' => '1',
  865. 'component' => $componentPath,
  866. 'children' => self::$menuChildren,
  867. ]
  868. ], $pid);
  869. }
  870. }
  871. public static function writeWebLangFile($langData, $webLangDir): void
  872. {
  873. foreach ($langData as $lang => $langDatum) {
  874. $langTsContent = '';
  875. foreach ($langDatum as $key => $item) {
  876. $quote = self::getQuote($item);
  877. $keyStr = self::formatObjectKey($key);
  878. $langTsContent .= self::tab() . $keyStr . ": $quote$item$quote,\n";
  879. }
  880. $langTsContent = "export default {\n" . $langTsContent . "}\n";
  881. self::writeFile(root_path() . $webLangDir[$lang] . '.ts', $langTsContent);
  882. }
  883. }
  884. public static function writeFile($path, $content): bool|int
  885. {
  886. $path = Filesystem::fsFit($path);
  887. if (!is_dir(dirname($path))) {
  888. mkdir(dirname($path), 0755, true);
  889. }
  890. return file_put_contents($path, $content);
  891. }
  892. public static function buildModelAppend($append): string
  893. {
  894. if (!$append) return '';
  895. $append = self::buildFormatSimpleArray($append);
  896. return "\n" . self::tab() . "// 追加属性" . "\n" . self::tab() . "protected \$append = $append;\n";
  897. }
  898. public static function buildModelFieldType(array $fieldType): string
  899. {
  900. if (!$fieldType) return '';
  901. $maxStrLang = 0;
  902. foreach ($fieldType as $key => $item) {
  903. $strLang = strlen($key);
  904. $maxStrLang = max($strLang, $maxStrLang);
  905. }
  906. $str = '';
  907. foreach ($fieldType as $key => $item) {
  908. $str .= self::tab(2) . "'$key'" . str_pad('=>', ($maxStrLang - strlen($key) + 3), ' ', STR_PAD_LEFT) . " '$item',\n";
  909. }
  910. return "\n" . self::tab() . "// 字段类型转换" . "\n" . self::tab() . "protected \$type = [\n" . rtrim($str, "\n") . "\n" . self::tab() . "];\n";
  911. }
  912. public static function writeModelFile(string $tablePk, array $fieldsMap, array $modelData, array $modelFile): void
  913. {
  914. if ($modelData['connection'] && $modelData['connection'] != config('database.default')) {
  915. $modelData['connection'] = "\n" . self::tab() . "// 数据库连接配置标识\n" . self::tab() . 'protected $connection = ' . "'{$modelData['connection']}';\n";
  916. } else {
  917. $modelData['connection'] = '';
  918. }
  919. $modelData['pk'] = $tablePk == 'id' ? '' : "\n" . self::tab() . "// 表主键\n" . self::tab() . 'protected $pk = ' . "'$tablePk';\n";
  920. $modelData['autoWriteTimestamp'] = array_key_exists(self::$createTimeField, $fieldsMap) || array_key_exists(self::$updateTimeField, $fieldsMap) ? 'true' : 'false';
  921. if ($modelData['autoWriteTimestamp'] == 'true') {
  922. $modelData['createTime'] = array_key_exists(self::$createTimeField, $fieldsMap) ? '' : "\n" . self::tab() . "protected \$createTime = false;";
  923. $modelData['updateTime'] = array_key_exists(self::$updateTimeField, $fieldsMap) ? '' : "\n" . self::tab() . "protected \$updateTime = false;";
  924. }
  925. $modelMethodList = isset($modelData['relationMethodList']) ? array_merge($modelData['methods'], $modelData['relationMethodList']) : $modelData['methods'];
  926. $modelData['methods'] = $modelMethodList ? "\n" . implode("\n", $modelMethodList) : '';
  927. $modelData['append'] = self::buildModelAppend($modelData['append']);
  928. $modelData['fieldType'] = self::buildModelFieldType($modelData['fieldType']);
  929. // 生成雪花ID?
  930. if (isset($modelData['beforeInsertMixins']['snowflake'])) {
  931. // beforeInsert 组装
  932. $modelData['beforeInsert'] = Helper::assembleStub('mixins/model/beforeInsert', [
  933. 'setSnowFlakeIdCode' => $modelData['beforeInsertMixins']['snowflake']
  934. ]);
  935. }
  936. if ($modelData['afterInsert'] && $modelData['beforeInsert']) {
  937. $modelData['afterInsert'] = "\n" . $modelData['afterInsert'];
  938. }
  939. $modelFileContent = self::assembleStub('mixins/model/model', $modelData);
  940. self::writeFile($modelFile['parseFile'], $modelFileContent);
  941. }
  942. public static function writeControllerFile(array $controllerData, array $controllerFile): void
  943. {
  944. if (isset($controllerData['relationVisibleFieldList']) && $controllerData['relationVisibleFieldList']) {
  945. $relationVisibleFields = '$res->visible([';
  946. foreach ($controllerData['relationVisibleFieldList'] as $cKey => $controllerDatum) {
  947. $relationVisibleFields .= "'$cKey' => ['" . implode("','", $controllerDatum) . "'], ";
  948. }
  949. $relationVisibleFields = rtrim($relationVisibleFields, ', ');
  950. $relationVisibleFields .= ']);';
  951. // 重写index
  952. $controllerData['methods']['index'] = self::assembleStub('mixins/controller/index', [
  953. 'relationVisibleFields' => $relationVisibleFields
  954. ]);
  955. $controllerData['use']['Throwable'] = "\nuse Throwable;";
  956. unset($controllerData['relationVisibleFieldList']);
  957. }
  958. $controllerAttr = '';
  959. foreach ($controllerData['attr'] as $key => $item) {
  960. $attrType = '';
  961. if (array_key_exists($key, self::$attrType['controller'])) {
  962. $attrType = self::$attrType['controller'][$key];
  963. }
  964. if (is_array($item)) {
  965. $controllerAttr .= "\n" . self::tab() . "protected $attrType \$$key = ['" . implode("', '", $item) . "'];\n";
  966. } elseif ($item) {
  967. $controllerAttr .= "\n" . self::tab() . "protected $attrType \$$key = '$item';\n";
  968. }
  969. }
  970. $controllerData['attr'] = $controllerAttr;
  971. $controllerData['initialize'] = self::assembleStub('mixins/controller/initialize', [
  972. 'modelNamespace' => $controllerData['modelNamespace'],
  973. 'modelName' => $controllerData['modelName'],
  974. 'filterRule' => $controllerData['filterRule'],
  975. ]);
  976. $contentFileContent = self::assembleStub('mixins/controller/controller', $controllerData);
  977. self::writeFile($controllerFile['parseFile'], $contentFileContent);
  978. }
  979. public static function writeFormFile($formVueData, $webViewsDir, $fields, $webTranslate): void
  980. {
  981. $fieldHtml = "\n";
  982. $formVueData['bigDialog'] = $formVueData['bigDialog'] ? "\n" . self::tab(2) . 'width="50%"' : '';
  983. foreach ($formVueData['formFields'] as $field) {
  984. $fieldHtml .= self::tab(5) . "<FormItem";
  985. foreach ($field as $key => $attr) {
  986. if (is_array($attr)) {
  987. $fieldHtml .= ' ' . $key . '="' . self::getJsonFromArray($attr) . '"';
  988. } else {
  989. $fieldHtml .= ' ' . $key . '="' . $attr . '"';
  990. }
  991. }
  992. $fieldHtml .= " />\n";
  993. }
  994. $formVueData['formFields'] = rtrim($fieldHtml, "\n");
  995. // 表单验证规则
  996. $formValidatorRules = [];
  997. foreach ($fields as $field) {
  998. if (isset($field['form']['validator'])) {
  999. foreach ($field['form']['validator'] as $item) {
  1000. $message = '';
  1001. if (isset($field['form']['validatorMsg']) && $field['form']['validatorMsg']) {
  1002. $message = ", message: '{$field['form']['validatorMsg']}'";
  1003. }
  1004. $formValidatorRules[$field['name']][] = "buildValidatorData({ name: '$item', title: t('$webTranslate{$field['name']}')$message })";
  1005. }
  1006. }
  1007. }
  1008. $formVueData['formItemRules'] = self::buildFormValidatorRules($formValidatorRules);
  1009. $formVueContent = self::assembleStub('html/form', $formVueData);
  1010. self::writeFile(root_path() . $webViewsDir['views'] . '/' . 'popupForm.vue', $formVueContent);
  1011. }
  1012. public static function buildFormValidatorRules($formValidatorRules): string
  1013. {
  1014. $rulesHtml = "";
  1015. foreach ($formValidatorRules as $key => $formItemRule) {
  1016. $rulesArrHtml = '';
  1017. foreach ($formItemRule as $item) {
  1018. $rulesArrHtml .= $item . ', ';
  1019. }
  1020. $rulesHtml .= self::tab() . $key . ': [' . rtrim($rulesArrHtml, ', ') . "],\n";
  1021. }
  1022. return $rulesHtml ? "\n" . $rulesHtml : '';
  1023. }
  1024. public static function writeIndexFile($indexVueData, $webViewsDir, $controllerFile): void
  1025. {
  1026. $indexVueData['optButtons'] = self::buildSimpleArray($indexVueData['optButtons']);
  1027. $indexVueData['defaultItems'] = self::getJsonFromArray($indexVueData['defaultItems']);
  1028. $indexVueData['tableColumn'] = self::buildTableColumn($indexVueData['tableColumn']);
  1029. $indexVueData['dblClickNotEditColumn'] = self::buildSimpleArray($indexVueData['dblClickNotEditColumn']);
  1030. $controllerFile['path'][] = $controllerFile['originalLastName'];
  1031. $indexVueData['controllerUrl'] = '\'/admin/' . ($controllerFile['path'] ? implode('.', $controllerFile['path']) : '') . '/\'';
  1032. $indexVueData['componentName'] = ($webViewsDir['path'] ? implode('/', $webViewsDir['path']) . '/' : '') . $webViewsDir['originalLastName'];
  1033. $indexVueContent = self::assembleStub('html/index', $indexVueData);
  1034. self::writeFile(root_path() . $webViewsDir['views'] . '/' . 'index.vue', $indexVueContent);
  1035. }
  1036. public static function buildTableColumn($tableColumnList): string
  1037. {
  1038. $columnJson = '';
  1039. foreach ($tableColumnList as $column) {
  1040. $columnJson .= self::tab(3) . '{';
  1041. foreach ($column as $key => $item) {
  1042. $columnJson .= self::buildTableColumnKey($key, $item);
  1043. }
  1044. $columnJson = rtrim($columnJson, ',');
  1045. $columnJson .= ' }' . ",\n";
  1046. }
  1047. return rtrim($columnJson, "\n");
  1048. }
  1049. public static function buildTableColumnKey($key, $item): string
  1050. {
  1051. $key = self::formatObjectKey($key);
  1052. if (is_array($item)) {
  1053. $itemJson = ' ' . $key . ': {';
  1054. foreach ($item as $ik => $iItem) {
  1055. $itemJson .= self::buildTableColumnKey($ik, $iItem);
  1056. }
  1057. $itemJson = rtrim($itemJson, ',');
  1058. $itemJson .= ' }';
  1059. } elseif ($item === 'false' || $item === 'true') {
  1060. $itemJson = ' ' . $key . ': ' . $item . ',';
  1061. } elseif (in_array($key, ['label', 'width', 'buttons'], true) || str_starts_with($item, "t('") || str_starts_with($item, "t(\"")) {
  1062. $itemJson = ' ' . $key . ': ' . $item . ',';
  1063. } else {
  1064. $itemJson = ' ' . $key . ': \'' . $item . '\',';
  1065. }
  1066. return $itemJson;
  1067. }
  1068. public static function formatObjectKey(string $keyName): string
  1069. {
  1070. if (preg_match("/^[a-zA-Z_][a-zA-Z0-9_]+$/", $keyName)) {
  1071. return $keyName;
  1072. } else {
  1073. $quote = self::getQuote($keyName);
  1074. return "$quote$keyName$quote";
  1075. }
  1076. }
  1077. public static function getQuote(string $value): string
  1078. {
  1079. return stripos($value, "'") === false ? "'" : '"';
  1080. }
  1081. public static function buildFormatSimpleArray($arr, int $tab = 2): string
  1082. {
  1083. if (!$arr) return '[]';
  1084. $str = '[' . PHP_EOL;
  1085. foreach ($arr as $item) {
  1086. if ($item == 'undefined' || $item == 'false' || is_numeric($item)) {
  1087. $str .= self::tab($tab) . $item . ',' . PHP_EOL;
  1088. } else {
  1089. $quote = self::getQuote($item);
  1090. $str .= self::tab($tab) . "$quote$item$quote," . PHP_EOL;
  1091. }
  1092. }
  1093. return $str . self::tab($tab - 1) . ']';
  1094. }
  1095. public static function buildSimpleArray($arr): string
  1096. {
  1097. if (!$arr) return '[]';
  1098. $str = '';
  1099. foreach ($arr as $item) {
  1100. if ($item == 'undefined' || $item == 'false' || is_numeric($item)) {
  1101. $str .= $item . ', ';
  1102. } else {
  1103. $quote = self::getQuote($item);
  1104. $str .= "$quote$item$quote, ";
  1105. }
  1106. }
  1107. return '[' . rtrim($str, ", ") . ']';
  1108. }
  1109. public static function buildDefaultOrder(string $field, string $type): string
  1110. {
  1111. if ($field && $type) {
  1112. $defaultOrderStub = [
  1113. 'prop' => $field,
  1114. 'order' => $type,
  1115. ];
  1116. $defaultOrderStub = self::getJsonFromArray($defaultOrderStub);
  1117. if ($defaultOrderStub) {
  1118. return "\n" . self::tab(2) . "defaultOrder: " . $defaultOrderStub . ',';
  1119. }
  1120. }
  1121. return '';
  1122. }
  1123. public static function getJsonFromArray($arr)
  1124. {
  1125. if (is_array($arr)) {
  1126. $jsonStr = '';
  1127. foreach ($arr as $key => $item) {
  1128. $keyStr = ' ' . self::formatObjectKey($key) . ': ';
  1129. if (is_array($item)) {
  1130. $jsonStr .= $keyStr . self::getJsonFromArray($item) . ',';
  1131. } elseif ($item === 'false' || $item === 'true') {
  1132. $jsonStr .= $keyStr . ($item === 'false' ? 'false' : 'true') . ',';
  1133. } elseif ($item === null) {
  1134. $jsonStr .= $keyStr . 'null,';
  1135. } elseif (str_starts_with($item, "t('") || str_starts_with($item, "t(\"") || $item == '[]' || in_array(gettype($item), ['integer', 'double'])) {
  1136. $jsonStr .= $keyStr . $item . ',';
  1137. } elseif (isset($item[0]) && $item[0] == '[' && str_ends_with($item, ']')) {
  1138. $jsonStr .= $keyStr . $item . ',';
  1139. } else {
  1140. $quote = self::getQuote($item);
  1141. $jsonStr .= $keyStr . "$quote$item$quote,";
  1142. }
  1143. }
  1144. return $jsonStr ? '{' . rtrim($jsonStr, ',') . ' }' : '{}';
  1145. } else {
  1146. return $arr;
  1147. }
  1148. }
  1149. }