Helper.php 47 KB

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