CommonDb.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Services\Interface\Database;
  4. use GuzzleHttp\Client;
  5. use Illuminate\Http\JsonResponse;
  6. use Illuminate\Support\Arr;
  7. use Illuminate\Support\Carbon;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Facades\Request;
  10. use Illuminate\Support\Str;
  11. use Txj\Elastic\Facades\ES;
  12. class CommonDb
  13. {
  14. protected array $requestData;
  15. protected string $table;
  16. /**
  17. * 接口信息.
  18. */
  19. protected array $interfaceInfo;
  20. protected array $interfaceSettingInfo = [];
  21. protected array $conditionSettingsInfo = [];
  22. protected array $interfaceResultInfo = [];
  23. /**
  24. * 集合信息.
  25. */
  26. protected array $assembleInfo = [];
  27. /**
  28. * 集合字段信息
  29. * 、@var array.
  30. */
  31. protected array $assembleColumns = [];
  32. /**
  33. * 字段id到字段编码的映射.
  34. */
  35. protected array $columnIdToCodes = [];
  36. public function __construct(array $interfaceInfo, array $assembleInfo, array $assembleColumns, array $requestData, array $columnIdToCodes)
  37. {
  38. $this->interfaceInfo = $interfaceInfo;
  39. $this->assembleInfo = $assembleInfo;
  40. $this->assembleColumns = $assembleColumns;
  41. $this->requestData = $requestData;
  42. $this->columnIdToCodes = $columnIdToCodes;
  43. $this->table = $this->assembleInfo['schema'];
  44. // 请求参数配置
  45. $this->interfaceSettingInfo = $this->interfaceInfo['request_settings'] ? json_decode($this->interfaceInfo['request_settings'], true) : [];
  46. // 条件配置
  47. $this->conditionSettingsInfo = $this->interfaceInfo['condition_settings'] ? json_decode($this->interfaceInfo['condition_settings'], true) : [];
  48. // 请求结果配置
  49. $this->interfaceResultInfo = $this->interfaceInfo['result_settings'] ? json_decode($this->interfaceInfo['result_settings'], true) : [];
  50. }
  51. /**
  52. * 获取部分字段.
  53. *
  54. * @param $find
  55. */
  56. public function getSelectFields(): array
  57. {
  58. $column_only_one = $this->interfaceResultInfo['column_only_one'] ?? false; // 是否直接返回单个字段
  59. $needFiledIds = $this->interfaceResultInfo['columns'] ?? []; // 需要返回的字段id
  60. $showColumnsArr = [];
  61. if ($column_only_one) {
  62. $showColumnsArr[] = $this->columnIdToCodes[$needFiledIds];
  63. } else {
  64. if ($needFiledIds) { // 将id,转为字段
  65. foreach ($needFiledIds as $column_id) {
  66. if (isset($this->columnIdToCodes[$column_id])) {
  67. $showColumnsArr[] = $this->columnIdToCodes[$column_id];
  68. }
  69. }
  70. }
  71. }
  72. return $showColumnsArr;
  73. }
  74. /**
  75. * 排序规则.
  76. *
  77. * @param $find
  78. */
  79. public function sortFields($find): void
  80. {
  81. $sortSettings = $this->interfaceInfo['sort_settings'] ?? '';
  82. if ($sortSettings) {
  83. foreach ($sortSettings as $row) {
  84. $column = $this->columnIdToCodes[$row['column_id']];
  85. // 转化为json字符串的方式 替换数组里面的模板变量
  86. $params = $this->replaceParams($this->requestData, $row);
  87. if (isset($row['is_allow']) && $row['is_allow']) {
  88. if (isset($this->requestData['sort_' . $column]) && \in_array($this->requestData['sort_' . $column], ['asc', 'desc'], true)) {
  89. $find->orderBy($column, $this->requestData['sort_' . $column], $params);
  90. } else {
  91. if (isset($row['direction']) && $row['direction']) {
  92. $find->orderBy($column, $row['direction'], $params);
  93. }
  94. }
  95. } else {
  96. if (isset($row['direction']) && $row['direction']) {
  97. $find->orderBy($column, $row['direction'], $params);
  98. }
  99. }
  100. }
  101. }
  102. }
  103. /**
  104. * 转化为json字符串的方式
  105. * 替换数组里面的模板变量.
  106. *
  107. * $requestData = [
  108. * 'sort_location' => 12,
  109. * 'sort_order' => 13,
  110. * ];
  111. *
  112. * $params = [
  113. * 'location' => [
  114. * 'lon' => '${location}',
  115. * 'lat' => '${order}',
  116. * ]
  117. * ];
  118. *
  119. * @param $requestData
  120. */
  121. private function replaceParams($requestData, ?array $row): mixed
  122. {
  123. $params = (isset($row['is_params']) && $row['is_params']) ? $row['params'] : [];
  124. if ($params) {
  125. $paramsJson = json_encode($params);
  126. preg_match_all('/\$\{(.*?)}/', $paramsJson, $arr);
  127. if ($arr && isset($arr[1])) {
  128. $flagArr = $arr[1];
  129. foreach ($flagArr as $row) {
  130. $value = $requestData['sort_' . $row] ?? '';
  131. $paramsJson = preg_replace('/\$\{' . $row . '}/', $value, $paramsJson, 1);
  132. }
  133. }
  134. return json_decode($paramsJson, true);
  135. }
  136. return $params;
  137. }
  138. // //////////////////////////////////////////////////////////////////////////////////////////////
  139. /**
  140. * 执行搜索的内容.
  141. */
  142. public function execSearchCon($find, $row): void
  143. {
  144. $es_type = $row['es_type'];
  145. $operate = $row['es_operate'];
  146. $childrenArr = $row['children'] ?? [];
  147. // 字段可能是数组,比如query_string
  148. if (\is_array($row['column_id'])) {
  149. foreach ($row['column_id'] as $id) {
  150. $column[] = $this->columnIdToCodes[$id];
  151. }
  152. } else {
  153. $column = $this->columnIdToCodes[$row['column_id']];
  154. }
  155. // 请求的参数,也有可能是数组,比如terms,range
  156. $value = [];
  157. if (\is_array($row['value'])) {
  158. foreach ($row['value'] as $name) {
  159. if (isset($this->requestData[$name])) {
  160. $value[] = $this->requestData[$name];
  161. } else {
  162. abort(508, '条件参数配置错误,' . $name . ' 值为空!');
  163. }
  164. }
  165. } else {
  166. if (isset($this->requestData[$row['value']])) {
  167. $value = $this->requestData[$row['value']];
  168. } else {
  169. // 如果没有值,忽略查询,如果不想忽略,则需要在请求参数设置为必填项
  170. // abort(508, '条件参数配置错误,' . $row['value'] . ' 值为空!');
  171. }
  172. }
  173. if ($value || 0 === $value) { // 如果值存在,则执行
  174. if (empty($childrenArr)) {
  175. $find->{$es_type}($column, $operate, $value);
  176. } else {
  177. $find->{$es_type}(function ($query) use ($childrenArr): void {
  178. if ($childrenArr) {
  179. foreach ($childrenArr as $child) {
  180. $this->execSearchCon($query, $child);
  181. }
  182. }
  183. });
  184. }
  185. }
  186. }
  187. // //////////////////////////////////////////////////////////////////////////////////////////////
  188. /**
  189. * 判断条件执行参数,根据if-elseif-else逻辑获取结果.
  190. *
  191. * @param string $searchOrResultType 判断是搜索内容处理,还是结果集内容管理
  192. */
  193. public function checkExpression(string $searchOrResultType, array $data, array $condition, $find = null): array|null
  194. {
  195. $expressionResult = null;
  196. // if else 转换为代码执行
  197. foreach ($condition as $judge) {
  198. // 参数
  199. $paramsArr = $judge['params'];
  200. $resultBool = $parentCurrent = true;
  201. foreach ($paramsArr as $key => $row) {
  202. if (0 == $key) {
  203. $resultBool = $parentCurrent = $this->execExpression($data, $row);
  204. } else {
  205. if ('and' == $row['type']) {
  206. if (true === $parentCurrent) {
  207. $resultBool = $parentCurrent = $this->execExpression($data, $row);
  208. } else {
  209. $resultBool = false;
  210. break;
  211. }
  212. } elseif ('or' == $row['type']) {
  213. if (true === $parentCurrent) {
  214. $resultBool = true;
  215. break;
  216. } else {
  217. $resultBool = $parentCurrent = $this->execExpression($data, $row);
  218. }
  219. }
  220. }
  221. }
  222. if ($resultBool) { // 为真,执行内容
  223. if ('search_type' == $searchOrResultType) {
  224. // 搜索内容管理
  225. $searchCon = $judge['searchCon'];
  226. foreach ($searchCon as $con) {
  227. $this->execSearchCon($find, $con);
  228. }
  229. break; // 搜索参数判断成功后,直接停止向下执行
  230. } elseif ('result_type' == $searchOrResultType) {
  231. $manageCon = $judge['manageCon'];
  232. foreach ($manageCon as $con) {
  233. $expressionResult = $this->execManageCon($data, $con);
  234. // 根据返回类型判断,有的需要直接返回,不再继续向下执行
  235. // 1 继续执行 2 错误退出 3 返回退出 4 使用结果 5 直接退出
  236. if ($responseJson = $this->checkBackType($expressionResult, $data)) {
  237. return $responseJson;
  238. }
  239. }
  240. }
  241. break;
  242. }
  243. }
  244. // 返回最后一次执行的结果
  245. return $expressionResult;
  246. }
  247. /**
  248. * 执行函数或表达式.
  249. */
  250. private function execExpression(array $data, array $row): bool
  251. {
  252. $operate = $row['operate'];
  253. if ($row['isUseFn']) { // 使用函数
  254. $fnName = $row['fnName'];
  255. $fnParams = $row['fnParams'];
  256. // 如果存在! 则先截取出来
  257. preg_match('/^(!*)(.*)/', $fnName, $fnArr);
  258. $flag = $fnArr[1];
  259. $fnName = $fnArr[2];
  260. foreach ($fnParams as $requestColumn) {
  261. $val = Arr::get($data, $requestColumn);
  262. if ($val) {
  263. $fParams[] = $val;
  264. } else {
  265. $fParams[] = $requestColumn;
  266. }
  267. }
  268. $result = $this->execFunc($fnName, $fParams);
  269. if ($result) {
  270. $current = true;
  271. } else {
  272. $current = false;
  273. }
  274. // ! 非操作符
  275. if ($flag) {
  276. if (1 == \strlen($flag) % 2) {
  277. $current = !$current;
  278. }
  279. }
  280. } else { // 表达式
  281. $requestVal = Arr::get($data, $row['params']);
  282. if ($requestVal || 0 === $requestVal || true === $requestVal || false === $requestVal) {
  283. $current = $this->getOperateResult($requestVal, $operate, $row['value']);
  284. } else {
  285. $current = false;
  286. }
  287. }
  288. return $current;
  289. }
  290. /**
  291. * 普通查询处理.
  292. *
  293. * @throws \GuzzleHttp\Exception\GuzzleException
  294. */
  295. private function execManageCon(array $data, array $con): array|null
  296. {
  297. $success_code = (isset($con['success_code']) && $con['success_code']) ? $con['success_code'] : 1001;
  298. $success_msg = (isset($con['success_msg']) && $con['success_msg']) ? $con['success_msg'] : '恭喜你,操作成功!';
  299. $failed_code = (isset($con['failed_code']) && $con['failed_code']) ? $con['failed_code'] : 2001;
  300. $failed_msg = (isset($con['failed_msg']) && $con['failed_msg']) ? $con['failed_msg'] : '操作失败,请稍后再试!';
  301. // 返回类型为5,直接返回,终止执行
  302. if (5 == $con['back_type']) {
  303. $backResult = backJson($failed_code, $failed_msg);
  304. return ['error' => false, 'back_type' => $con['back_type'], 'result' => $backResult];
  305. }
  306. $requestParams = [];
  307. if (isset($con['column']) && $con['column']) {
  308. foreach ($con['column'] as $requestColumn) {
  309. $val = Arr::get($data, $requestColumn);
  310. if ($val) {
  311. $requestParams[$requestColumn] = $val;
  312. } else {
  313. $requestParams[] = $requestColumn; // 如果值不存在,则当前字段,会作为值来处理
  314. }
  315. }
  316. }
  317. // 防止非法参数向下传递
  318. Request::replace($requestParams);
  319. $param_type = $con['param_type']; // 1 接口 2 函数 3 自定义接口
  320. if (1 == $param_type) { // 接口
  321. $result = $this->execInterface($con['interface_id']);
  322. } elseif (2 == $param_type) { // 函数
  323. $result = $this->execFunc($con['fnName'], array_values($requestParams));
  324. } elseif (3 == $param_type) { // 自定义接口
  325. $result = $this->execCustomInterface($con['url'], $requestParams);
  326. }
  327. if ($result instanceof JsonResponse) {
  328. $backResult = json_decode($result->getContent(), true);
  329. return ['error' => $backResult['error'], 'back_type' => $con['back_type'], 'result' => $backResult];
  330. } elseif (empty($result) || (isset($result['error']) && $result['error'])) {
  331. $backResult = backJson($result['code'] ?? $failed_code, $result['msg'] ?? $failed_msg);
  332. return ['error' => true, 'back_type' => $con['back_type'], 'result' => $backResult];
  333. } else {
  334. $backResult = backJson($success_code, $success_msg, isset($result['error']) ? $result['result'] : $result);
  335. return ['error' => false, 'back_type' => $con['back_type'], 'flag_uuid' => $con['flag_uuid'] ?? '', 'result' => $backResult];
  336. }
  337. }
  338. /**
  339. * 执行函数.
  340. */
  341. private function execFunc(string $function, array $params = []): mixed
  342. {
  343. if (empty($function)) {
  344. abort(508, '结果集设置错误!- 函数为空');
  345. }
  346. if (($flag1 = Str::contains($function, '@')) || Str::contains($function, '::')) {
  347. $arr = explode($flag1 ? '@' : '::', $function);
  348. $class = $arr[0] ?? '';
  349. $method = $arr[1] ?? 'handler';
  350. if ($class && class_exists($class)) {
  351. if ($flag1) {
  352. return \call_user_func_array([new $class($this->requestData, $this->interfaceInfo, $this->websiteInfo, $this->assembleInfo, $this->assembleColumns), $method], $params);
  353. } else {
  354. return \call_user_func_array([$class, $method], $params);
  355. }
  356. } else {
  357. abort(508, '接口参数设置错误!- 类【' . $class . '】不存在');
  358. }
  359. } elseif (\function_exists($function)) { // 如果是函数,则使用函数处理,参数:当前字段信息,接口信息,站点信息
  360. return \call_user_func_array($function, $params);
  361. }
  362. return '';
  363. }
  364. /**
  365. * 请求系统接口.
  366. *
  367. * @throws \Exception
  368. */
  369. private function execInterface(int $interfaceId): mixed
  370. {
  371. if (empty($interfaceId)) {
  372. abort(508, '结果集设置错误!- 设置的接口为空!');
  373. }
  374. // 获取接口信息
  375. $otherInterfaceInfo = ES::table('interface')->find($interfaceId);
  376. if ($otherInterfaceInfo) {
  377. $interfaceService = new static($otherInterfaceInfo['en_alias'], $this->websiteInfo);
  378. $errorMsg = $interfaceService->validator();
  379. if ($errorMsg) {
  380. abort(508, '结果集设置错误!- ' . $errorMsg);
  381. } else {
  382. $response = $interfaceService->exec();
  383. return json_decode($response->getContent(), true);
  384. }
  385. } else {
  386. abort(508, '结果集设置错误!- 设置的接口不存在');
  387. }
  388. }
  389. /**
  390. * 请求自定义接口.
  391. *
  392. * @throws \Exception
  393. */
  394. private function execCustomInterface(string $url, array $params = []): mixed
  395. {
  396. if (empty($url)) {
  397. abort(508, '结果集设置错误!- 设置的接口为空!');
  398. }
  399. $method = 'POST';
  400. $options = [
  401. 'json' => $params,
  402. 'timeout' => 60,
  403. 'verify' => false,
  404. ];
  405. if (!Str::startsWith($url, 'http')) {
  406. if (Str::contains($url, '/')) { // 为了过滤通过route(name)生成的url
  407. $url = secure_url($url);
  408. } else {
  409. // 路由名生成一个 URL
  410. $url = route($url);
  411. }
  412. }
  413. $client = new Client();
  414. return $client->request($method, $url, $options);
  415. }
  416. /**
  417. * 根据返回类型判断,有的需要直接返回,不再继续向下执行
  418. * 1 继续执行 2 错误退出 3 返回退出 4 使用结果 5 直接退出.
  419. *
  420. * @throws \Exception
  421. */
  422. private function checkBackType($expressionResult, &$data)
  423. {
  424. // 如果未设置任何参数,则不做任何处理,允许代码继续向下执行
  425. if (empty($expressionResult)) {
  426. return null;
  427. }
  428. // 1 继续执行 2 错误退出 3 返回退出 4 使用结果 5 直接退出
  429. $back_type = $expressionResult['back_type'];
  430. $flag_uuid = $expressionResult['flag_uuid'] ?? '';
  431. $backResult = $expressionResult['result'];
  432. if (2 == $back_type) {
  433. if (true === $backResult['error']) { // 如果出现错误,则返回错误信息
  434. $backResult['error'] = $backResult['error'] ?: '系统错误,请重试!';
  435. return $expressionResult;
  436. }
  437. } elseif (3 == $back_type) {
  438. return $expressionResult;
  439. } elseif (4 == $back_type) {
  440. $data[] = ['&' . $flag_uuid => $backResult];
  441. } elseif (5 == $back_type) {
  442. $backResult['error'] = $backResult['error'] ?: '系统错误,请重试!';
  443. return $expressionResult;
  444. }
  445. }
  446. /**
  447. * 操作符的操作结果.
  448. */
  449. private function getOperateResult(mixed $requestVal, string $operate, mixed $value): bool
  450. {
  451. return match ($operate) {
  452. 'true' => true == $requestVal,
  453. 'false' => false == $requestVal,
  454. '==' => $requestVal == $value,
  455. '>' => $requestVal > $value,
  456. '<' => $requestVal < $value,
  457. '>=' => $requestVal >= $value,
  458. '<=' => $requestVal <= $value,
  459. '!=' => $requestVal != $value,
  460. '===' => $requestVal === $value,
  461. '!==' => $requestVal !== $value,
  462. 'in' => \in_array($value, $requestVal),
  463. default => false,
  464. };
  465. }
  466. // //////////////////////////////////////////////////////////////////////////////////////////////
  467. // //////////////////////////////////////////////////////////////////////////////////////////////
  468. /**
  469. * 兼容 eav 模式,获取表对象
  470. */
  471. private function getDbObject(): \Illuminate\Database\Query\Builder
  472. {
  473. return DB::table($this->table);
  474. }
  475. /**
  476. * 添加数据时 获取表对应的数据信息.
  477. */
  478. public function getTableToData(string $sysType, array $data): array
  479. {
  480. // 获取所有的属性
  481. $tableToData = []; // 过滤数据
  482. $tableEntityData = []; // 存在子表数据的信息
  483. foreach ($this->assembleColumns as $attributeInfo) {
  484. $attrId = $attributeInfo['id'];
  485. $type = $attributeInfo['type'];
  486. $code = $attributeInfo['code'];
  487. // 判断字段是否存在 非法字段进行过滤
  488. if (!\array_key_exists($code, $data)) {
  489. continue;
  490. }
  491. $value = $data[$code];
  492. if ('' === $value) {
  493. $value = $attributeInfo['default'] ?? '';
  494. }
  495. // 强制类型转换
  496. if (\in_array($type, ['integer', 'tinyInteger', 'smallInteger', 'mediumInteger', 'bigInteger'], true)) {
  497. $value = (int)$value;
  498. } elseif ('decimal' === $type) {
  499. $value = (float)$value;
  500. }
  501. if ('object' === $type || 'json' === $type) { // array 数据转换
  502. if (!\is_array($value)) {
  503. abort(509, '【' . $attributeInfo['code'] . '】数据必须为数组!- 01');
  504. }
  505. $tableEntityData[$code] = json_encode($value);
  506. } else {
  507. $tableEntityData[$code] = $value;
  508. }
  509. }
  510. // 系统固有字段进行修复
  511. $sysEntity = $this->getSysEntityData($data, $sysType);
  512. $tableEntityData = array_merge($sysEntity, $tableEntityData);
  513. return [$tableToData, $tableEntityData];
  514. }
  515. /**
  516. * 获取实体数据.
  517. */
  518. public function getSysEntityData(array $requestData, string $type = 'add'): array
  519. {
  520. $entityData = [];
  521. $timestampMs = Carbon::now()->getTimestamp(); // 获取当前时间的毫秒数
  522. if ('add' == $type) {
  523. if (isset($requestData['id']) && $requestData['id']) {
  524. $entityData['id'] = $requestData['id'];
  525. }
  526. }
  527. if (!isset($requestData['mid'])) {
  528. if ('add' == $type) {
  529. $entityData['mid'] = Str::random(12);
  530. }
  531. } else {
  532. $entityData['mid'] = $requestData['mid'];
  533. }
  534. if (!isset($requestData['created_at'])) {
  535. if ('add' == $type) {
  536. $entityData['created_at'] = $timestampMs;
  537. }
  538. } else {
  539. $entityData['created_at'] = $requestData['created_at'];
  540. }
  541. if (!isset($requestData['is_delete'])) {
  542. if ('add' == $type) {
  543. $entityData['is_delete'] = 0;
  544. }
  545. } else {
  546. $entityData['is_delete'] = $requestData['is_delete'];
  547. }
  548. if (!isset($requestData['weight'])) {
  549. if ('add' == $type) {
  550. $entityData['weight'] = 0;
  551. }
  552. } else {
  553. $entityData['weight'] = $requestData['weight'];
  554. }
  555. $entityData['updated_at'] = $timestampMs; // 获取当前时间的毫秒数
  556. return $entityData;
  557. }
  558. /**
  559. * 设置该集合对应的数据库连接.
  560. */
  561. public function getDbConnection(): ?string
  562. {
  563. return DB::getDefaultConnection();
  564. }
  565. }