helpers.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. <?php
  2. use Carbon\Carbon;
  3. use Illuminate\Http\Request;
  4. use Illuminate\Support\Arr;
  5. use Illuminate\Support\Facades\Session;
  6. use Illuminate\Support\Facades\Cookie;
  7. use Illuminate\Support\Str;
  8. if (! function_exists('user_admin_config')) {
  9. function user_admin_config($key = null, $value = null)
  10. {
  11. // 获取 session 实例
  12. $session = session();
  13. // 从 session 中获取 'admin.config',如果没有则使用默认的 'admin' 配置
  14. $config = $session->get('admin.config', function () {
  15. $adminConfig = config('admin');
  16. $adminConfig['lang'] = config('app.locale');
  17. return $adminConfig;
  18. });
  19. // 如果 $key 是数组,表示我们需要批量设置配置项
  20. if (is_array($key)) {
  21. foreach ($key as $k => $v) {
  22. Arr::set($config, $k, $v); // 在配置数组中设置每个键值对
  23. }
  24. $session->put('admin.config', $config); // 将更新后的配置保存到 session 中
  25. return;
  26. }
  27. // 如果没有传递具体的 key,返回整个配置数组
  28. if (is_null($key)) {
  29. return $config;
  30. }
  31. // 获取指定的配置项,如果不存在则返回默认值 $value
  32. return Arr::get($config, $key, $value);
  33. }
  34. }
  35. if (! function_exists('switchLanguage')) {
  36. function switchLanguage($lang)
  37. {
  38. // 验证是否是支持的语言
  39. if (!in_array($lang, ['en', 'zh_CN', 'zh_TW'])) {
  40. return false;
  41. }
  42. Cookie::queue('lang', $lang, 60 * 24 * 30); // 保存 30 天
  43. // 动态修改 app.locale 配置
  44. config(['app.locale' => $lang]);
  45. return true;
  46. }
  47. }
  48. if (!function_exists('getDistributor')) {
  49. /**
  50. * 获取会话中的 distributor 值
  51. *
  52. * @return mixed
  53. */
  54. function getDistributor() {
  55. return Session::get('distributor');
  56. }
  57. }
  58. if (!function_exists('getDistributorDomain')) {
  59. function getDistributorDomain()
  60. {
  61. $domain = '';
  62. $row = getDistributor();
  63. if ($row) {
  64. if ($row['domain_type'] == 0) {
  65. $domain = 'https://'.$row['secondary_domain'];
  66. } else {
  67. $domain = 'https://'.$row['custom_domain'];
  68. }
  69. }
  70. // if (env('DIST_SITE_PORT') != 80) {
  71. // $domain .= ':' . env('DIST_SITE_PORT');
  72. // }
  73. return $domain;
  74. }
  75. }
  76. if (!function_exists('getDistributorId')) {
  77. /**
  78. * 获取会话中的 distributor 的 ID
  79. *
  80. * @return mixed
  81. */
  82. function getDistributorId() {
  83. $distributor = Session::get('distributor');
  84. return $distributor ? $distributor['id'] : null; // 假设 distributor 是一个数组,包含 id
  85. }
  86. }
  87. /*
  88. * 使用session记录与显示临时变量,变量名在config/dictionary.php中的temp_value
  89. */
  90. if (!function_exists('setTempValue')) {
  91. function setTempValue($key, $value) {
  92. $arr = config('dictionary.temp_value');
  93. if (isset($arr[$key])) {
  94. $newKey = '_temp_value_'.$key;//加前缀
  95. Session::put($newKey, $value);
  96. return true;
  97. }
  98. return false;
  99. }
  100. }
  101. /*
  102. * 拿临时变量
  103. */
  104. if (!function_exists('getTempValue')) {
  105. function getTempValue($key) {
  106. $arr = config('dictionary.temp_value');
  107. if (isset($arr[$key])) {
  108. $newKey = '_temp_value_'.$key; //加前缀
  109. $value = Session::get($newKey);
  110. return $value === null ? $arr[$key] : $value;
  111. }
  112. return false;
  113. }
  114. }
  115. if (!function_exists('getSiteDomain')) {
  116. //得到分销商域名
  117. function getSiteDomain($hasHttp = true) {
  118. $distributor = Session::get('distributor');
  119. $domain = $distributor['domain_type'] == 0 ? $distributor['secondary_domain'] : $domain = $distributor['custom_domain'];
  120. if ($hasHttp) {
  121. $domain = 'https://'.$domain;
  122. }
  123. return $domain;
  124. }
  125. }
  126. //通过parent_id构建树形结构
  127. if (!function_exists('buildTree')) {
  128. function buildTree(array $elements, $parentId = 0)
  129. {
  130. $branch = [];
  131. foreach ($elements as $element) {
  132. if ($element['parent_id'] == $parentId) {
  133. $children = buildTree($elements, $element['id']);
  134. if ($children) {
  135. $element['children'] = $children;
  136. }
  137. $branch[] = $element;
  138. }
  139. }
  140. return $branch;
  141. }
  142. }
  143. // 展平树形结构
  144. if (!function_exists('flattenTree')) {
  145. function flattenTree(array $tree, array &$result = [], $level = 0)
  146. {
  147. foreach ($tree as $node) {
  148. // 复制节点数据,但不包括子节点,并添加 level 字段
  149. $flattenedNode = array_diff_key($node, ['children' => null]);
  150. $flattenedNode['level'] = $level;
  151. $result[] = $flattenedNode;
  152. // 如果有子节点,递归处理子节点,并将 level 增加 1
  153. if (isset($node['children']) && is_array($node['children'])) {
  154. flattenTree($node['children'], $result, $level + 1);
  155. }
  156. }
  157. return $result;
  158. }
  159. }
  160. if (!function_exists('uniqueCode')) {
  161. function uniqueCode($prefix = '')
  162. {
  163. //$uniqueId = strtolower(Str::random($length));
  164. $uniqueId = uniqid($prefix);
  165. return $uniqueId;
  166. }
  167. }
  168. if (!function_exists('generateVersionNumber')) {
  169. /*
  170. * 12位版本号
  171. */
  172. function generateVersionNumber()
  173. {
  174. // 获取当前的年、月、日
  175. $year = date('y'); // 年份的最后两位
  176. $month = date('m'); // 月份,两位数字
  177. $day = date('d'); // 日期,两位数字
  178. // 获取当前的毫秒级时间戳
  179. $microtime = microtime(true);
  180. $milliseconds = round(($microtime - floor($microtime)) * 1000);
  181. // 将毫秒级时间戳转换为 6 位数字
  182. $milliseconds = str_pad($milliseconds, 3, '0', STR_PAD_LEFT);
  183. // 获取当前的时间戳(秒级)
  184. $timestamp = time();
  185. // 将时间戳转换为 6 位数字(如果需要更精确的时间戳,可以使用毫秒级时间戳)
  186. $timestamp = str_pad($timestamp % 1000000, 6, '0', STR_PAD_LEFT);
  187. // 组合成 12 位版本号
  188. $versionNumber = $year . $month . $day. $timestamp. $milliseconds ;
  189. return $versionNumber;
  190. }
  191. }
  192. //判断是否为json
  193. if (!function_exists('isValidJson')) {
  194. function isValidJson($string) {
  195. json_decode($string);
  196. return (json_last_error() === JSON_ERROR_NONE);
  197. }
  198. }
  199. //判断是否为纯域名
  200. if (!function_exists('isDomainOnly')) {
  201. function isDomainOnly($string) {
  202. // 正则表达式:匹配不带协议或路径的纯域名
  203. $pattern = '/^(?!:\/\/)([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$/';
  204. return preg_match($pattern, $string) === 1;
  205. }
  206. }
  207. //生成slug
  208. if (!function_exists('generateSlug')) {
  209. function generateSlug($title)
  210. {
  211. // 1. 将所有字符转换为小写
  212. $slug = strtolower($title);
  213. // 2. 将空格替换为短横线(-)
  214. $slug = str_replace(' ', '-', $slug);
  215. // 3. 将不合法的字符(!@#$%^&*?=+)替换为空
  216. $slug = preg_replace('/[::^!@#$%^&*()?=+]+/u', '', $slug);
  217. // 4. 清理多余的短横线
  218. $slug = preg_replace('/-+/', '-', $slug);
  219. // 5. 去除开头和结尾的短横线
  220. $slug = trim($slug, '-');
  221. return $slug;
  222. }
  223. }
  224. //生成随机小写英文组成的字符串
  225. if (!function_exists('generateRandomString')) {
  226. function generateRandomString($length = 3) {
  227. $characters = 'abcdefghijklmnopqrstuvwxyz';
  228. $charactersLength = strlen($characters);
  229. $randomString = '';
  230. for ($i = 0; $i < $length; $i++) {
  231. $randomString .= $characters[rand(0, $charactersLength - 1)];
  232. }
  233. return $randomString;
  234. }
  235. }
  236. //翻译数组
  237. if (!function_exists('admin_trans_array')) {
  238. function admin_trans_array($array) {
  239. array_walk($array, function(&$value, $key) {
  240. $value = admin_trans_label($value);
  241. });
  242. return $array;
  243. }
  244. }
  245. //curl get
  246. if (!function_exists('curlGet')) {
  247. function curlGet($url,$timeout=10) {
  248. $ch = curl_init();
  249. curl_setopt($ch, CURLOPT_URL, $url);
  250. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
  251. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  252. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  253. $response = curl_exec($ch);
  254. if ($response === false) {
  255. return array(
  256. 'error' => curl_error($ch),
  257. 'http_code' => null
  258. );
  259. } else {
  260. $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  261. return array(
  262. 'response' => $response,
  263. 'http_code' => $http_code
  264. );
  265. }
  266. curl_close($ch);
  267. }
  268. }
  269. /*
  270. * 截取字符函数
  271. * $string 要截取的字符串
  272. * $length 截取长度
  273. * $append 后缀
  274. */
  275. if (!function_exists('truncateString')) {
  276. function truncateString($string, $length = 30, $append = '') {
  277. // 检查字符串长度是否超过指定长度
  278. if (mb_strlen($string, 'UTF-8') > $length) {
  279. // 截取字符串
  280. $truncated = mb_substr($string, 0, $length, 'UTF-8');
  281. // 添加省略号
  282. return $truncated . $append;
  283. }
  284. // 如果字符串长度小于或等于指定长度,直接返回原字符串
  285. return $string;
  286. }
  287. }
  288. /*
  289. * 带http的url转化为storage_path路径
  290. */
  291. if (!function_exists('toStoragePath')) {
  292. function toStoragePath($httpUrl) {
  293. $parsed = parse_url($httpUrl);
  294. $path = ltrim($parsed['path'], '/');
  295. return storage_path('app/'.$path);
  296. }
  297. }
  298. /*
  299. * 将UTC时间转换为当前浏览器时区时间
  300. * 空,返回当前浏览器时间
  301. */
  302. if (!function_exists('utcToLocalTime')) {
  303. function utcToLocalTime($utcTime = '') {
  304. $timeZoneName = Session::get('timeZoneName') ?? 'UTC';
  305. if (empty($utcTime)) {
  306. return Carbon::now($timeZoneName)->format('Y-m-d H:i:s');
  307. }
  308. // 创建 UTC 时区对象
  309. $utcTimezone = new DateTimeZone('UTC');
  310. // 解析输入时间(支持字符串和时间戳)
  311. if (is_numeric($utcTime)) {
  312. $date = DateTime::createFromFormat('U', $utcTime, $utcTimezone);
  313. } else {
  314. $date = DateTime::createFromFormat('Y-m-d H:i:s', $utcTime, $utcTimezone);
  315. }
  316. // 转换到时区
  317. $distTimezone = new DateTimeZone($timeZoneName);
  318. $date->setTimezone($distTimezone);
  319. return $date->format('Y-m-d H:i:s');
  320. }
  321. }
  322. /*
  323. * 将当前浏览器时区时间转换为UTC时间
  324. * 空返回当前的UTC时间
  325. */
  326. if (!function_exists('localTimeToUtc')) {
  327. function localTimeToUtc($inputTime = '') {
  328. if (empty($inputTime)) {
  329. return Carbon::now('UTC')->format('Y-m-d H:i:s');
  330. }
  331. $timeZoneName = Session::get('timeZoneName') ?? 'UTC';
  332. // 创建分销商时区对象
  333. $distTimezone = new DateTimeZone($timeZoneName);
  334. // 解析输入时间(支持字符串和时间戳)
  335. if (is_numeric($inputTime)) {
  336. $date = DateTime::createFromFormat('U', $inputTime, $distTimezone);
  337. } else {
  338. $date = DateTime::createFromFormat('Y-m-d H:i:s', $inputTime, $distTimezone);
  339. }
  340. // 转换到 UTC 时区
  341. $date->setTimezone(new DateTimeZone('UTC'));
  342. return $date->format('Y-m-d H:i:s');
  343. }
  344. }