Service.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. <?php
  2. namespace App\Service;
  3. use Illuminate\Support\Facades\Redis;
  4. use Illuminate\Support\Facades\Storage;
  5. /**
  6. * 公用的公共服务
  7. * @package App\Models
  8. */
  9. class Service
  10. {
  11. public $log;
  12. public $total = 0;
  13. public function __construct()
  14. {
  15. }
  16. //分页共用
  17. public function limit($db, $columns, $request)
  18. {
  19. $per_page = $request['page_size'] ?? 100;
  20. $page = $request['page_index'] ?? 1;
  21. $return = $db->paginate($per_page, $columns, 'page', $page)->toArray();
  22. $data['total'] = $return['total'];
  23. $data['data'] = $return['data'];
  24. return $data;
  25. }
  26. //分页共用2
  27. public function limitData($db, $columns, $request)
  28. {
  29. $per_page = $request['page_size'] ?? 1000;
  30. $page = $request['page_index'] ?? 1;
  31. $return = $db->paginate($per_page, $columns, 'page', $page)->toArray();
  32. return $return['data'];
  33. }
  34. //抽象一个查询条件,省的每天写很多行
  35. protected function is_exist_db($data, $word, $words, $db, $formula = '=', $type = '')
  36. {
  37. if (isset($data[$word]) && ($data[$word] !== null && $data[$word] !== '' && $data[$word] !== [])) {
  38. switch ($type) {
  39. case 'time':
  40. $data[$word] = ctype_digit($data[$word]) ? $data[$word] : strtotime($data[$word]);
  41. if ($formula == '<'||$formula == '<=') $data[$word] += 86400;
  42. $db = $db->where($words, $formula, $data[$word]);
  43. break;
  44. case 'like':
  45. $db = $db->where($words, $type, '%' . $data[$word] . '%');
  46. break;
  47. case 'in':
  48. if (is_array($data[$word])) {
  49. $db = $db->wherein($words, $data[$word]);
  50. } else {
  51. $db = $db->wherein($words, explode(',', $data[$word]));
  52. }
  53. break;
  54. default:
  55. $db = $db->where($words, $formula, $data[$word]);
  56. break;
  57. }
  58. return $db;
  59. }
  60. return $db;
  61. }
  62. //判断是否为空
  63. protected function isEmpty($data, $word)
  64. {
  65. if (isset($data[$word]) && (!empty($data[$word]) || $data[$word] === '0'|| $data[$word] === 0)) return false;
  66. return true;
  67. }
  68. //递归处理数据成子父级关系
  69. public function makeTree($parentId, &$node)
  70. {
  71. $tree = [];
  72. foreach ($node as $key => $value) {
  73. if ($value['parent_id'] == $parentId) {
  74. $tree[$value['id']] = $value;
  75. unset($node[$key]);
  76. if (isset($tree[$value['id']]['children'])) {
  77. $tree[$value['id']]['children'] = array_merge($tree[$value['id']]['children'], $this->makeTree($value['id'], $node));
  78. } else {
  79. $tree[$value['id']]['children'] = $this->makeTree($value['id'], $node);
  80. }
  81. }
  82. }
  83. return $tree;
  84. }
  85. //进行递归处理数组的排序问题
  86. public function set_sort_circle($data){
  87. foreach ($data as $k=>$v){
  88. // var_dump($v);die;
  89. if(isset($v['children'])&&!empty($v['children'])){
  90. $data[$k]['children'] = $this->set_sort_circle($v['children']);
  91. }
  92. }
  93. $data = array_merge($data);
  94. return $data;
  95. }
  96. //根据编码规则获取每一级的code
  97. public function get_rule_code($code, $rule)
  98. {
  99. $rules = [];
  100. $num = 0;
  101. foreach ($rule as $v) {
  102. $num += $v['num'];
  103. $code = substr($code, 0, $num);
  104. if (strlen($code) != $num) continue;
  105. $rules[] = $code;
  106. }
  107. return $rules;
  108. }
  109. function curlOpen($url, $config = array())
  110. {
  111. $arr = array('post' => false,'referer' => $url,'cookie' => '', 'useragent' => 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; customie8)', 'timeout' => 100, 'return' => true, 'proxy' => '', 'userpwd' => '', 'nobody' => false,'header'=>array(),'gzip'=>true,'ssl'=>true,'isupfile'=>false,'returnheader'=>false,'request'=>'post');
  112. $arr = array_merge($arr, $config);
  113. $ch = curl_init();
  114. curl_setopt($ch, CURLOPT_URL, $url);
  115. curl_setopt($ch, CURLOPT_RETURNTRANSFER, $arr['return']);
  116. curl_setopt($ch, CURLOPT_NOBODY, $arr['nobody']);
  117. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  118. curl_setopt($ch, CURLOPT_USERAGENT, $arr['useragent']);
  119. curl_setopt($ch, CURLOPT_REFERER, $arr['referer']);
  120. curl_setopt($ch, CURLOPT_TIMEOUT, $arr['timeout']);
  121. curl_setopt($ch, CURLOPT_HEADER, $arr['returnheader']);//��ȡheader
  122. if($arr['gzip']) curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
  123. if($arr['ssl'])
  124. {
  125. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  126. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  127. }
  128. if(!empty($arr['cookie']))
  129. {
  130. curl_setopt($ch, CURLOPT_COOKIEJAR, $arr['cookie']);
  131. curl_setopt($ch, CURLOPT_COOKIEFILE, $arr['cookie']);
  132. }
  133. if(!empty($arr['proxy']))
  134. {
  135. //curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  136. curl_setopt ($ch, CURLOPT_PROXY, $arr['proxy']);
  137. if(!empty($arr['userpwd']))
  138. {
  139. curl_setopt($ch,CURLOPT_PROXYUSERPWD,$arr['userpwd']);
  140. }
  141. }
  142. //ip�Ƚ����⣬�ü�ֵ��ʾ
  143. if(!empty($arr['header']['ip']))
  144. {
  145. array_push($arr['header'],'X-FORWARDED-FOR:'.$arr['header']['ip'],'CLIENT-IP:'.$arr['header']['ip']);
  146. unset($arr['header']['ip']);
  147. }
  148. $arr['header'] = array_filter($arr['header']);
  149. if(!empty($arr['header']))
  150. {
  151. curl_setopt($ch, CURLOPT_HTTPHEADER, $arr['header']);
  152. }
  153. if($arr['request'] === 'put'){
  154. curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
  155. curl_setopt($ch, CURLOPT_POSTFIELDS,$arr['post']);
  156. }elseif($arr['post'] != false)
  157. {
  158. curl_setopt($ch, CURLOPT_POST, true);
  159. if(is_array($arr['post']) && $arr['isupfile'] === false)
  160. {
  161. $post = http_build_query($arr['post']);
  162. }
  163. else
  164. {
  165. $post = $arr['post'];
  166. }
  167. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  168. }
  169. $result = curl_exec($ch);
  170. curl_close($ch);
  171. return $result;
  172. }
  173. function getAllIdsArr($data, $pid = 0, $prefix = '', &$result = []) {
  174. foreach ($data as $node) {
  175. if ($node['parent_id'] == $pid) {
  176. $id = $prefix . $node['id'];
  177. $result[] = $id;
  178. $this->getAllIdsArr($data, $node['id'], $id . ',', $result);
  179. }
  180. }
  181. return $result;
  182. }
  183. function getLongestStr($arr = [], $searchStr){
  184. if(empty($arr) || ! $searchStr) return '';
  185. if(! is_string($searchStr)) $searchStr = (string)$searchStr;
  186. $longest = '';
  187. foreach ($arr as $str) {
  188. if (strpos($str, $searchStr) !== false && strlen($str) > strlen($longest)) {
  189. $longest = $str;
  190. }
  191. }
  192. return $longest;
  193. }
  194. function getAllDescendants($data, $id) {
  195. $result = array(); // 存储结果的数组
  196. foreach ($data as $node) {
  197. if ($node['parent_id'] == $id) { // 如果当前节点的父 ID 等于指定 ID,则将该节点添加到结果中
  198. $result[] = $node['id'];
  199. // 递归查询该节点的所有子孙节点,并将结果合并到结果数组中
  200. $result = array_merge($result, $this->getAllDescendants($data, $node['id']));
  201. }
  202. }
  203. return $result;
  204. }
  205. //后台端 某些需要限制请求频率的接口
  206. //需要主动删除 Redis::del($key)
  207. public function limitingSendRequest($key,$value=0){
  208. $prefix = config('app.name') . ':';
  209. $key = $prefix . $key;
  210. if(! empty($value)) $value = 1;
  211. // 使用Redis Facade设置,当键名不存在时才设置成功
  212. if (Redis::setnx($key, $value)) return [true, ''];
  213. return [false,'操作频繁!'];
  214. }
  215. public function delLimitingSendRequest($key){
  216. $prefix = config('app.name') . ':';
  217. $key = $prefix . $key;
  218. Redis::del($key);
  219. }
  220. //后台端 某些需要限制请求频率的接口 有过期时间
  221. public function limitingSendRequestBackgExpire($key,$ttl = 5){
  222. $prefix = config('app.name') . ':';
  223. $key = $prefix . $key;
  224. if($ttl < 5) $ttl = 5;
  225. // 使用Redis Facade设置,当键名不存在时才设置成功
  226. if (Redis::setnx($key, 1)) {
  227. Redis::expire($key, $ttl); //多少秒后过期
  228. return [true, ''];
  229. }
  230. return [false,'操作频繁, 请在 ' . $ttl . '秒后重试'];
  231. }
  232. //前端传来的时间段 转换为时间戳
  233. //精确到秒
  234. function changeDateToTimeStampAboutRange($time_range, $is_end = true){
  235. if(empty($time_range[0]) || empty($time_range[1])) return [];
  236. // 创建一个 DateTime 对象并设置时区为 UTC
  237. $dateTime = new \DateTime($time_range[0], new \DateTimeZone('UTC'));
  238. $dateTime1 = new \DateTime($time_range[1], new \DateTimeZone('UTC'));
  239. // 将时区设置为 PRC
  240. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  241. $dateTime1->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  242. // 将日期时间格式化为特定格式
  243. $formattedDate = $dateTime->format('Y-m-d');
  244. $formattedDate1 = $dateTime1->format('Y-m-d');
  245. $str = " 23:59:59";
  246. if(! $is_end) $str = " 00:00:00";
  247. $return = [];
  248. $return[] = strtotime($formattedDate . " 00:00:00");
  249. $return[] = strtotime($formattedDate1 . $str);
  250. return $return;
  251. }
  252. //前端传来的时间段 转换为时间戳
  253. //精确到日
  254. function changeDateToNewDate($time_range){
  255. if(empty($time_range[0]) || empty($time_range[1])) return [];
  256. // 创建一个 DateTime 对象并设置时区为 UTC
  257. $dateTime = new \DateTime($time_range[0], new \DateTimeZone('UTC'));
  258. $dateTime1 = new \DateTime($time_range[1], new \DateTimeZone('UTC'));
  259. // 将时区设置为 PRC
  260. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  261. $dateTime1->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  262. // 将日期时间格式化为特定格式
  263. $formattedDate = $dateTime->format('Y-m-d');
  264. $formattedDate1 = $dateTime1->format('Y-m-d');
  265. $return = [];
  266. $return[] = strtotime($formattedDate);
  267. $return[] = strtotime($formattedDate1);
  268. return $return;
  269. }
  270. function changeDateToNewDate2($time){
  271. if(empty($time_range)) return [];
  272. // 创建一个 DateTime 对象并设置时区为 UTC
  273. $dateTime = new \DateTime($time_range, new \DateTimeZone('UTC'));
  274. // 将时区设置为 PRC
  275. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  276. // 将日期时间格式化为特定格式
  277. $formattedDate = $dateTime->format('Y-m-d 00:00:00');
  278. $formattedDate1 = $dateTime->format('Y-m-d 23:59:59');
  279. $return = [];
  280. $return[] = strtotime($formattedDate);
  281. $return[] = strtotime($formattedDate1);
  282. return $return;
  283. }
  284. //前端传来的时间 转为时间戳
  285. //精确到分
  286. function changeDateToDateMin($time){
  287. if(empty($time)) return '';
  288. // 创建一个 DateTime 对象并设置时区为 UTC
  289. $dateTime = new \DateTime($time, new \DateTimeZone('UTC'));
  290. // 将时区设置为 PRC
  291. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  292. // 将日期时间格式化为特定格式
  293. $formattedDate = $dateTime->format('Y-m-d H:i');
  294. return strtotime($formattedDate);
  295. }
  296. function changeDateToMonth($time)
  297. {
  298. if (empty($time)) {
  299. return 0; // 或抛出异常,根据业务决定
  300. }
  301. // 解析输入时间,默认按 UTC 解析(兼容前端 ISO 字符串)
  302. $dateTime = new \DateTime($time, new \DateTimeZone('UTC'));
  303. // 转换为上海时区(PRC)
  304. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  305. // 设置为当月第一天,00:00:00
  306. $dateTime->modify('first day of this month');
  307. $dateTime->setTime(0, 0, 0);
  308. return $dateTime->getTimestamp(); // 推荐使用 getTimestamp() 而非 strtotime
  309. }
  310. //前端传来的时间 转为时间戳
  311. //精确到日
  312. function changeDateToDate($time, $is_end = false){
  313. if(empty($time)) return '';
  314. // 创建一个 DateTime 对象并设置时区为 UTC
  315. $dateTime = new \DateTime($time, new \DateTimeZone('UTC'));
  316. // 将时区设置为 PRC
  317. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  318. $str = "00:00:00";
  319. if($is_end) $str = "23:59:59";
  320. // 将日期时间格式化为特定格式
  321. $formattedDate = $dateTime->format('Y-m-d ' . $str);
  322. return strtotime($formattedDate);
  323. }
  324. /**
  325. * 检查数字是否合法,并可验证其正负性和小数位数
  326. *
  327. * @param mixed $number 要检查的值
  328. * @param int $decimals 允许的最大小数位数(默认 2)
  329. * @param string|null $sign 要求的符号:'positive' 大于 0 , 'negative' 小于0, 'zero' 等于0, 'non-negative' 大于或等于 0, 'non-positive' 小于或等于 0 null 表示不限制
  330. * @param bool $strict 是否严格模式(不允许整数传字符串等)
  331. * @return array ['valid' => bool, 'error' => string|null, 'info' => array]
  332. */
  333. public function checkNumber($number, $decimals = 2, $sign = null, $strict = false)
  334. {
  335. $result = [
  336. 'valid' => false,
  337. 'error' => null,
  338. 'info' => []
  339. ];
  340. // 1. 类型检查
  341. if ($strict) {
  342. if (!is_numeric($number) || is_bool($number)) {
  343. $result['error'] = '必须是数字类型';
  344. return $result;
  345. }
  346. } else {
  347. // 宽松模式:允许字符串数字
  348. if (!is_numeric($number)) {
  349. $result['error'] = '不是有效数字';
  350. return $result;
  351. }
  352. }
  353. $num = (float)$number; // 统一转为浮点数处理
  354. // 2. 正负号检查
  355. if ($sign !== null) {
  356. switch ($sign) {
  357. case 'positive':
  358. if ($num <= 0) {
  359. $result['error'] = '数字必须大于 0';
  360. return $result;
  361. }
  362. break;
  363. case 'negative':
  364. if ($num >= 0) {
  365. $result['error'] = '数字必须小于 0';
  366. return $result;
  367. }
  368. break;
  369. case 'zero':
  370. if ($num != 0) {
  371. $result['error'] = '数字必须等于 0';
  372. return $result;
  373. }
  374. break;
  375. case 'non-negative': // 大于等于 0
  376. if ($num < 0) {
  377. $result['error'] = '数字必须大于或等于 0';
  378. return $result;
  379. }
  380. break;
  381. case 'non-positive': // 小于等于 0
  382. if ($num > 0) {
  383. $result['error'] = '数字必须小于或等于 0';
  384. return $result;
  385. }
  386. break;
  387. default:
  388. $result['error'] = "不支持的符号类型: '{$sign}'";
  389. return $result;
  390. }
  391. }
  392. // 3. 小数位数检查
  393. // 将数字转为标准格式,避免科学计数法
  394. $numStr = rtrim(rtrim(sprintf('%.10F', $num), '0'), '.'); // 去除末尾无意义的0
  395. if ($numStr === '' || $numStr === '-') {
  396. $numStr = '0';
  397. }
  398. // 检查是否有小数点
  399. if (strpos($numStr, '.') === false) {
  400. $decimalPlaces = 0;
  401. } else {
  402. $parts = explode('.', $numStr);
  403. $decimalPlaces = strlen($parts[1]);
  404. }
  405. if ($decimalPlaces > $decimals) {
  406. $result['error'] = "小数位数超过 {$decimals} 位(实际 {$decimalPlaces} 位)";
  407. return $result;
  408. }
  409. // 4. 附加信息
  410. $result['valid'] = true;
  411. $result['info'] = [
  412. 'original' => $number,
  413. 'value' => $num,
  414. 'decimal_places' => $decimalPlaces,
  415. 'sign' => $num > 0 ? 'positive' : ($num < 0 ? 'negative' : 'zero'),
  416. ];
  417. return $result;
  418. }
  419. public function getTopId($id, $data) {
  420. foreach ($data as $item) {
  421. if ($item['id'] == $id) {
  422. if ($item['parent_id'] == 0) {
  423. // 找到最顶级的id
  424. return $item['id'];
  425. } else {
  426. // 继续递归查找父级
  427. return $this->getTopId($item['parent_id'], $data);
  428. }
  429. }
  430. }
  431. // 如果没有找到匹配的id,则返回null或者其他你希望的默认值
  432. return 0;
  433. }
  434. // 递归查找所有父级id
  435. public function findParentIds($id, $data) {
  436. $parentIds = [];
  437. foreach ($data as $item) {
  438. if ($item['id'] == $id) {
  439. $parentId = $item['parent_id'];
  440. if ($parentId) {
  441. $parentIds[] = $parentId;
  442. $parentIds = array_merge($parentIds, $this->findParentIds($parentId, $data));
  443. }
  444. break;
  445. }
  446. }
  447. return $parentIds;
  448. }
  449. // 递归查找所有子级id
  450. public function findChildIds($id, $data) {
  451. $childIds = [];
  452. foreach ($data as $item) {
  453. if ($item['parent_id'] == $id) {
  454. $childId = $item['id'];
  455. $childIds[] = $childId;
  456. $childIds = array_merge($childIds, $this->findChildIds($childId, $data));
  457. }
  458. }
  459. return $childIds;
  460. }
  461. public function getDataFile($data){
  462. foreach ($data as $key => $value){
  463. if($key == 'depart_id' || $key == 'top_depart_id') unset($data[$key]);
  464. }
  465. return $data;
  466. }
  467. // 校验域名是否通畅可达
  468. // $domain baidu.com 不要带http这些协议头
  469. // gethostbyname() 函数可能会受到 PHP 配置中的 allow_url_fopen 和 disable_functions 选项的限制
  470. function isDomainAvailable($domain) {
  471. $ip = gethostbyname($domain);
  472. // 如果解析失败或者返回的 IP 地址与输入的域名相同,则说明域名无效
  473. if ($ip === $domain || filter_var($ip, FILTER_VALIDATE_IP) === false) return false;
  474. return true;
  475. }
  476. public function delStorageFile($old, $new = [], $dir = "upload_files/"){
  477. foreach ($old as $value){
  478. if(! in_array($value, $new)){
  479. $filename_rep = "/api/uploadFiles/";
  480. $filename = str_replace($filename_rep, "", $value);
  481. $filePath = $dir . $filename;
  482. if (Storage::disk('public')->exists($filePath)) {
  483. // 文件存在 进行删除操作
  484. Storage::disk('public')->delete($filePath);
  485. }
  486. }
  487. }
  488. }
  489. public function showTimeAgo($time, $time_big){
  490. // 计算时间差(秒)
  491. $diffInSeconds = $time_big - $time;
  492. // 将时间差转换为更易处理的单位
  493. $diffInMinutes = floor($diffInSeconds / 60);
  494. $diffInHours = floor($diffInSeconds / 3600);
  495. $diffInDays = floor($diffInSeconds / (3600 * 24));
  496. // 根据时间差生成描述性文本
  497. if ($diffInSeconds < 60) {
  498. $timeAgo = '刚刚';
  499. } elseif ($diffInMinutes < 60) {
  500. $timeAgo = $diffInMinutes . '分钟前';
  501. } elseif ($diffInHours < 24) {
  502. $timeAgo = $diffInHours . '小时前';
  503. } elseif ($diffInDays < 2) {
  504. $timeAgo = '昨天';
  505. } elseif ($diffInDays < 7) {
  506. $timeAgo = $diffInDays . '天前';
  507. } elseif ($diffInDays < 15) {
  508. $timeAgo = '一周前';
  509. } elseif ($diffInDays < 30) {
  510. $timeAgo = '半个月内';
  511. } else {
  512. // 如果超过半个月,可以使用具体的日期格式
  513. $crtTimeDate = date('Y-m-d', $time);
  514. $timeAgo = '在 ' . $crtTimeDate;
  515. }
  516. return $timeAgo;
  517. }
  518. // 递归函数,用于在数据结构中查找值
  519. function findLabelsByValue($data, $valuesToFind, &$foundLabels) {
  520. foreach ($data as $item) {
  521. if (isset($item['value']) && in_array($item['value'], $valuesToFind)) {
  522. // 如果找到值,则添加其label到结果数组中
  523. $foundLabels[] = $item['label'];
  524. // 移除已找到的值,避免重复查找
  525. $key = array_search($item['value'], $valuesToFind);
  526. if ($key !== false) {
  527. unset($valuesToFind[$key]);
  528. }
  529. }
  530. if (isset($item['children']) && !empty($item['children'])) {
  531. // 递归调用自身来查找子节点
  532. $this->findLabelsByValue($item['children'], $valuesToFind, $foundLabels);
  533. }
  534. // 如果所有值都已找到,则停止递归
  535. if (empty($valuesToFind)) {
  536. break;
  537. }
  538. }
  539. }
  540. public function changeAndReturnDate($date_int){
  541. $int = intval($date_int);
  542. $bool = (string)$int === $date_int;
  543. if(! $bool || $date_int < 0) return [false, '日期不正确'];
  544. $epoch = strtotime("1900-01-01 00:00:00");
  545. $days = $date_int - 1;
  546. $seconds = $days * 86400;
  547. return [true,strtotime(date('Y-m-d 00:00:00', $epoch + $seconds))];
  548. }
  549. function findTopLevelId($data, $id) {
  550. // 遍历数据,查找给定ID的节点
  551. foreach ($data as $item) {
  552. if ($item['id'] == $id) {
  553. // 如果找到了给定ID的节点,并且它的parent_id为null,则它就是最顶层节点
  554. if ($item['parent_id'] === 0) {
  555. return $item['id'];
  556. } else {
  557. // 否则,继续寻找其父节点的最顶层节点
  558. return $this->findTopLevelId($data, $item['parent_id']);
  559. }
  560. }
  561. }
  562. // 如果没有找到给定ID的节点,返回null或抛出异常
  563. return 0;
  564. }
  565. function returnDays($time = [], $is_mirco_time = false){
  566. // 示例时间戳
  567. $timestamp1 = $time[0];
  568. $timestamp2 = $time[1];
  569. // 计算时间差
  570. $difference = abs($timestamp2 - $timestamp1);
  571. // 将时间差转换为天数
  572. $days = floor($difference / (60 * 60 * 24));
  573. if($is_mirco_time) $days = $days / 1000;
  574. return $days;
  575. }
  576. public function post_helper($url, $data, $header = [], $timeout = 30){
  577. $ch = curl_init();
  578. curl_setopt($ch, CURLOPT_URL, $url);
  579. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  580. curl_setopt($ch, CURLOPT_ENCODING, '');
  581. curl_setopt($ch, CURLOPT_POST, 1);
  582. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
  583. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  584. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  585. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  586. if(!is_null($data)) curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  587. $r = curl_exec($ch);
  588. if ($r === false) {
  589. // 获取错误号
  590. $errorNumber = curl_errno($ch);
  591. // 获取错误信息
  592. $errorMessage = curl_error($ch);
  593. $message = "cURL Error #{$errorNumber}: {$errorMessage}";
  594. return [false, $message];
  595. }
  596. curl_close($ch);
  597. return [true, json_decode($r, true)];
  598. }
  599. function isOverThreeMonths($timestamp1, $timestamp2, $default_month = 3) {
  600. $date1 = new \DateTime();
  601. $date1->setTimestamp($timestamp1);
  602. $date2 = new \DateTime();
  603. $date2->setTimestamp($timestamp2);
  604. // 计算两个日期的间隔
  605. $interval = $date1->diff($date2);
  606. // 总月数 = 年差 * 12 + 月差
  607. $months = $interval->y * 12 + $interval->m;
  608. if ($months >= $default_month) {
  609. return [false, "时间区间须在" . $default_month . "个月内"];
  610. }elseif ($months == 3 && ($interval->d > 0 || $interval->h > 0 || $interval->i > 0 || $interval->s > 0)) {
  611. return [false, "时间区间须在" . $default_month . "个月内"];
  612. }
  613. return [true, ''];
  614. }
  615. public function countTotal($rows, $config = [])
  616. {
  617. if (empty($rows)) return [];
  618. $total = [];
  619. foreach ($config as $col) {
  620. $key = $col['key'] ?? null;
  621. if (!$key) continue;
  622. $decimals = $col['decimals'] ?? 2; // 默认保留 2 位
  623. // 1. 基础字段累加
  624. if (!empty($col['sum']) && $col['sum'] == 1) {
  625. $sum = '0';
  626. foreach ($rows as $row) {
  627. $sum = bcadd($sum, (string)($row[$key] ?? 0), $decimals);
  628. }
  629. $total[$key] = $sum;
  630. }
  631. // 2. 公式字段
  632. if (!empty($col['sum']) && $col['sum'] == 2 && !empty($col['formula'])) {
  633. $total[$key] = $this->calcFormula($col['formula'], $total, $decimals);
  634. }
  635. }
  636. return $total;
  637. }
  638. /**
  639. * 解析并计算公式(基于 bcmath)
  640. * 例: profit / income * 100
  641. */
  642. public function calcFormula($formula, $values, $decimals = 2)
  643. {
  644. $tokens = preg_split('/\s+/', trim($formula));
  645. $stack = [];
  646. foreach ($tokens as $token) {
  647. if ($token === '') continue;
  648. if (isset($values[$token])) {
  649. $stack[] = $values[$token];
  650. } elseif (is_numeric($token)) {
  651. $stack[] = (string)$token;
  652. } else {
  653. $stack[] = $token;
  654. }
  655. }
  656. $expr = implode(' ', $stack);
  657. return $this->evaluateWithBCMath($expr, $decimals);
  658. }
  659. public function evaluateWithBCMath2($expr, $decimals = 2)
  660. {
  661. $calcDecimals = 8; // 中间计算用更高精度
  662. // 支持负数和小数
  663. preg_match_all('/-?\d+(?:\.\d+)?|[+\/*-]/', $expr, $matches);
  664. $tokens = $matches[0] ?? [];
  665. if (empty($tokens)) return '0';
  666. // Shunting-yard 算法转换为逆波兰表达式 (RPN)
  667. $output = [];
  668. $ops = [];
  669. $precedence = ['+' => 1, '-' => 1, '*' => 2, '/' => 2];
  670. foreach ($tokens as $token) {
  671. if (is_numeric($token)) {
  672. $output[] = (string)$token;
  673. } elseif (isset($precedence[$token])) {
  674. while (!empty($ops) && $precedence[end($ops)] >= $precedence[$token]) {
  675. $output[] = array_pop($ops);
  676. }
  677. $ops[] = $token;
  678. }
  679. }
  680. while (!empty($ops)) {
  681. $output[] = array_pop($ops);
  682. }
  683. // 计算 RPN
  684. $stack = [];
  685. foreach ($output as $token) {
  686. if (is_numeric($token)) {
  687. $stack[] = (string)$token;
  688. } else {
  689. $b = array_pop($stack) ?? '0';
  690. $a = array_pop($stack) ?? '0';
  691. switch ($token) {
  692. case '+':
  693. $stack[] = bcadd($a, $b, $calcDecimals);
  694. break;
  695. case '-':
  696. $stack[] = bcsub($a, $b, $calcDecimals);
  697. break;
  698. case '*':
  699. $stack[] = bcmul($a, $b, $calcDecimals);
  700. break;
  701. case '/':
  702. if (bccomp($b, '0', $calcDecimals) === 0) {
  703. $stack[] = '0';
  704. } else {
  705. $stack[] = bcdiv($a, $b, $calcDecimals);
  706. }
  707. break;
  708. }
  709. }
  710. }
  711. $result = array_pop($stack) ?? '0';
  712. // 最终统一格式化为指定小数位
  713. return bcadd($result, '0', $decimals);
  714. }
  715. public function evaluateWithBCMath($expr, $decimals = 2)
  716. {
  717. $calcDecimals = 8; // 中间计算精度更高
  718. // ✅ 使用 ~ 作为正则分隔符,避免与除号 / 冲突
  719. preg_match_all('~-?\d+(?:\.\d+)?|[+\-*/()]~', $expr, $matches);
  720. $tokens = $matches[0] ?? [];
  721. if (empty($tokens)) return '0';
  722. // 运算符优先级
  723. $precedence = ['+' => 1, '-' => 1, '*' => 2, '/' => 2];
  724. // === Shunting Yard 算法 ===
  725. $output = [];
  726. $ops = [];
  727. $prevToken = null;
  728. foreach ($tokens as $token) {
  729. if (is_numeric($token)) {
  730. $output[] = $token;
  731. } elseif ($token === '(') {
  732. $ops[] = $token;
  733. } elseif ($token === ')') {
  734. while (!empty($ops) && end($ops) !== '(') {
  735. $output[] = array_pop($ops);
  736. }
  737. array_pop($ops); // 弹出 (
  738. } elseif (isset($precedence[$token])) {
  739. // 一元负号处理
  740. if ($token === '-' && ($prevToken === null || $prevToken === '(' || isset($precedence[$prevToken]))) {
  741. $output[] = '0';
  742. }
  743. while (!empty($ops) && isset($precedence[end($ops)]) && $precedence[end($ops)] >= $precedence[$token]) {
  744. $output[] = array_pop($ops);
  745. }
  746. $ops[] = $token;
  747. }
  748. $prevToken = $token;
  749. }
  750. while (!empty($ops)) {
  751. $output[] = array_pop($ops);
  752. }
  753. // === 计算逆波兰表达式 ===
  754. $stack = [];
  755. foreach ($output as $token) {
  756. if (is_numeric($token)) {
  757. $stack[] = $token;
  758. } else {
  759. $b = array_pop($stack) ?? '0';
  760. $a = array_pop($stack) ?? '0';
  761. switch ($token) {
  762. case '+':
  763. $stack[] = bcadd($a, $b, $calcDecimals);
  764. break;
  765. case '-':
  766. $stack[] = bcsub($a, $b, $calcDecimals);
  767. break;
  768. case '*':
  769. $stack[] = bcmul($a, $b, $calcDecimals);
  770. break;
  771. case '/':
  772. $stack[] = (bccomp($b, '0', $calcDecimals) === 0)
  773. ? '0'
  774. : bcdiv($a, $b, $calcDecimals);
  775. break;
  776. }
  777. }
  778. }
  779. $result = array_pop($stack) ?? '0';
  780. return bcadd($result, '0', $decimals);
  781. }
  782. public function checkArrayRepeat($data, $column, $title = ""){
  783. $ids = array_column($data, $column);
  784. // 检查空值
  785. if (in_array('', $ids, true) || in_array(null, $ids, true)) {
  786. return [false, $title . '不能为空'];
  787. }
  788. // 检查重复
  789. if (count($ids) !== count(array_unique($ids))) {
  790. return [false, $title . '不能重复'];
  791. }
  792. return [true, ''];
  793. }
  794. function isValidPhone($phone) {
  795. return preg_match('/^1(3\d|4[5-9]|5[0-35-9]|6[5-7]|7[0-8]|8\d|9[0-35-9])\d{8}$/', $phone);
  796. }
  797. }