Service.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. <?php
  2. namespace App\Service;
  3. use Illuminate\Support\Facades\Redis;
  4. /**
  5. * 公用的公共服务
  6. * @package App\Models
  7. */
  8. class Service
  9. {
  10. public $log;
  11. public $total = 0;
  12. public function __construct()
  13. {
  14. }
  15. //分页共用
  16. public function limit($db, $columns, $request)
  17. {
  18. $per_page = $request['page_size'] ?? 9999;
  19. $page = $request['page_index'] ?? 1;
  20. $return = $db->paginate($per_page, $columns, 'page', $page)->toArray();
  21. $data['total'] = $return['total'];
  22. $data['data'] = $return['data'];
  23. return $data;
  24. }
  25. //抽象一个查询条件,省的每天写很多行
  26. protected function is_exist_db($data, $word, $words, $db, $formula = '=', $type = '')
  27. {
  28. if (isset($data[$word]) && ($data[$word] !== null && $data[$word] !== '' && $data[$word] !== [])) {
  29. switch ($type) {
  30. case 'time':
  31. $data[$word] = ctype_digit($data[$word]) ? $data[$word] : strtotime($data[$word]);
  32. if ($formula == '<'||$formula == '<=') $data[$word] += 86400;
  33. $db = $db->where($words, $formula, $data[$word]);
  34. break;
  35. case 'like':
  36. $db = $db->where($words, $type, '%' . $data[$word] . '%');
  37. break;
  38. case 'in':
  39. if (is_array($data[$word])) {
  40. $db = $db->wherein($words, $data[$word]);
  41. } else {
  42. $db = $db->wherein($words, explode(',', $data[$word]));
  43. }
  44. break;
  45. default:
  46. $db = $db->where($words, $formula, $data[$word]);
  47. break;
  48. }
  49. return $db;
  50. }
  51. return $db;
  52. }
  53. //判断是否为空
  54. protected function isEmpty($data, $word)
  55. {
  56. if (isset($data[$word]) && (!empty($data[$word]) || $data[$word] === '0'|| $data[$word] === 0)) return false;
  57. return true;
  58. }
  59. //递归处理数据成子父级关系
  60. public function makeTree($parentId, &$node)
  61. {
  62. $tree = [];
  63. foreach ($node as $key => $value) {
  64. if ($value['parent_id'] == $parentId) {
  65. $tree[$value['id']] = $value;
  66. unset($node[$key]);
  67. if (isset($tree[$value['id']]['children'])) {
  68. $tree[$value['id']]['children'] = array_merge($tree[$value['id']]['children'], $this->makeTree($value['id'], $node));
  69. } else {
  70. $tree[$value['id']]['children'] = $this->makeTree($value['id'], $node);
  71. }
  72. }
  73. }
  74. return $tree;
  75. }
  76. //进行递归处理数组的排序问题
  77. public function set_sort_circle($data){
  78. foreach ($data as $k=>$v){
  79. // var_dump($v);die;
  80. if(isset($v['children'])&&!empty($v['children'])){
  81. $data[$k]['children'] = $this->set_sort_circle($v['children']);
  82. }
  83. }
  84. $data = array_merge($data);
  85. return $data;
  86. }
  87. //根据编码规则获取每一级的code
  88. public function get_rule_code($code, $rule)
  89. {
  90. $rules = [];
  91. $num = 0;
  92. foreach ($rule as $v) {
  93. $num += $v['num'];
  94. $code = substr($code, 0, $num);
  95. if (strlen($code) != $num) continue;
  96. $rules[] = $code;
  97. }
  98. return $rules;
  99. }
  100. function curlOpen($url, $config = array())
  101. {
  102. $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');
  103. $arr = array_merge($arr, $config);
  104. $ch = curl_init();
  105. curl_setopt($ch, CURLOPT_URL, $url);
  106. curl_setopt($ch, CURLOPT_RETURNTRANSFER, $arr['return']);
  107. curl_setopt($ch, CURLOPT_NOBODY, $arr['nobody']);
  108. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  109. curl_setopt($ch, CURLOPT_USERAGENT, $arr['useragent']);
  110. curl_setopt($ch, CURLOPT_REFERER, $arr['referer']);
  111. curl_setopt($ch, CURLOPT_TIMEOUT, $arr['timeout']);
  112. curl_setopt($ch, CURLOPT_HEADER, $arr['returnheader']);//��ȡheader
  113. if($arr['gzip']) curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
  114. if($arr['ssl'])
  115. {
  116. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  117. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  118. }
  119. if(!empty($arr['cookie']))
  120. {
  121. curl_setopt($ch, CURLOPT_COOKIEJAR, $arr['cookie']);
  122. curl_setopt($ch, CURLOPT_COOKIEFILE, $arr['cookie']);
  123. }
  124. if(!empty($arr['proxy']))
  125. {
  126. //curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  127. curl_setopt ($ch, CURLOPT_PROXY, $arr['proxy']);
  128. if(!empty($arr['userpwd']))
  129. {
  130. curl_setopt($ch,CURLOPT_PROXYUSERPWD,$arr['userpwd']);
  131. }
  132. }
  133. //ip�Ƚ����⣬�ü�ֵ��ʾ
  134. if(!empty($arr['header']['ip']))
  135. {
  136. array_push($arr['header'],'X-FORWARDED-FOR:'.$arr['header']['ip'],'CLIENT-IP:'.$arr['header']['ip']);
  137. unset($arr['header']['ip']);
  138. }
  139. $arr['header'] = array_filter($arr['header']);
  140. if(!empty($arr['header']))
  141. {
  142. curl_setopt($ch, CURLOPT_HTTPHEADER, $arr['header']);
  143. }
  144. if($arr['request'] === 'put'){
  145. curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
  146. curl_setopt($ch, CURLOPT_POSTFIELDS,$arr['post']);
  147. }elseif($arr['post'] != false)
  148. {
  149. curl_setopt($ch, CURLOPT_POST, true);
  150. if(is_array($arr['post']) && $arr['isupfile'] === false)
  151. {
  152. $post = http_build_query($arr['post']);
  153. }
  154. else
  155. {
  156. $post = $arr['post'];
  157. }
  158. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  159. }
  160. $result = curl_exec($ch);
  161. curl_close($ch);
  162. return $result;
  163. }
  164. function getAllIdsArr($data, $pid = 0, $prefix = '', &$result = []) {
  165. foreach ($data as $node) {
  166. if ($node['parent_id'] == $pid) {
  167. $id = $prefix . $node['id'];
  168. $result[] = $id;
  169. $this->getAllIdsArr($data, $node['id'], $id . ',', $result);
  170. }
  171. }
  172. return $result;
  173. }
  174. function getLongestStr($arr = [], $searchStr){
  175. if(empty($arr) || ! $searchStr) return '';
  176. if(! is_string($searchStr)) $searchStr = (string)$searchStr;
  177. $longest = '';
  178. foreach ($arr as $str) {
  179. if (strpos($str, $searchStr) !== false && strlen($str) > strlen($longest)) {
  180. $longest = $str;
  181. }
  182. }
  183. return $longest;
  184. }
  185. function getAllDescendants($data, $id) {
  186. $result = array(); // 存储结果的数组
  187. foreach ($data as $node) {
  188. if ($node['parent_id'] == $id) { // 如果当前节点的父 ID 等于指定 ID,则将该节点添加到结果中
  189. $result[] = $node['id'];
  190. // 递归查询该节点的所有子孙节点,并将结果合并到结果数组中
  191. $result = array_merge($result, $this->getAllDescendants($data, $node['id']));
  192. }
  193. }
  194. return $result;
  195. }
  196. function changeDateToDateMin($time){
  197. if(empty($time)) return '';
  198. // 创建一个 DateTime 对象并设置时区为 UTC
  199. $dateTime = new \DateTime($time, new \DateTimeZone('UTC'));
  200. // 将时区设置为 PRC
  201. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  202. // 将日期时间格式化为特定格式
  203. $formattedDate = $dateTime->format('Y-m-d H:i:s');
  204. return $formattedDate;
  205. }
  206. //后台端 某些需要限制请求频率的接口
  207. //需要主动删除 Redis::del($key)
  208. public function limitingSendRequestBackgNeed($key,$value=0){
  209. $prefix = config('app.name') . ':';
  210. $key = $prefix . $key;
  211. if(! empty($value)) $value = 1;
  212. // 使用Redis Facade设置,当键名不存在时才设置成功
  213. if (Redis::setnx($key, $value)) return [true, ''];
  214. return [false,'操作频繁!'];
  215. }
  216. public function dellimitingSendRequestBackgNeed($key){
  217. $prefix = config('app.name') . ':';
  218. $key = $prefix . $key;
  219. Redis::del($key);
  220. }
  221. // 校验域名是否通畅可达
  222. // $domain baidu.com 不要带http这些协议头
  223. // gethostbyname() 函数可能会受到 PHP 配置中的 allow_url_fopen 和 disable_functions 选项的限制
  224. function isDomainAvailable($domain) {
  225. $ip = gethostbyname($domain);
  226. // 如果解析失败或者返回的 IP 地址与输入的域名相同,则说明域名无效
  227. if ($ip === $domain || filter_var($ip, FILTER_VALIDATE_IP) === false) return false;
  228. return true;
  229. }
  230. function changeDateToDate($time, $is_end = false){
  231. if(empty($time)) return '';
  232. // 创建一个 DateTime 对象并设置时区为 UTC
  233. $dateTime = new \DateTime($time, new \DateTimeZone('UTC'));
  234. // 将时区设置为 PRC
  235. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  236. $str = "00:00:00";
  237. if($is_end) $str = "23:59:59";
  238. // 将日期时间格式化为特定格式
  239. $formattedDate = $dateTime->format('Y-m-d ' . $str);
  240. return strtotime($formattedDate);
  241. }
  242. //前端传来的时间段 转换为时间戳
  243. //精确到秒
  244. function changeDateToTimeStampAboutRange($time_range, $is_end = true){
  245. if(empty($time_range[0]) || empty($time_range[1])) return [];
  246. // 创建一个 DateTime 对象并设置时区为 UTC
  247. $dateTime = new \DateTime($time_range[0], new \DateTimeZone('UTC'));
  248. $dateTime1 = new \DateTime($time_range[1], new \DateTimeZone('UTC'));
  249. // 将时区设置为 PRC
  250. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  251. $dateTime1->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  252. // 将日期时间格式化为特定格式
  253. $formattedDate = $dateTime->format('Y-m-d');
  254. $formattedDate1 = $dateTime1->format('Y-m-d');
  255. $str = " 23:59:59";
  256. if(! $is_end) $str = " 00:00:00";
  257. $return = [];
  258. $return[] = strtotime($formattedDate . " 00:00:00");
  259. $return[] = strtotime($formattedDate1 . $str);
  260. return $return;
  261. }
  262. /**
  263. * 检查数字是否合法,并可验证其正负性和小数位数
  264. *
  265. * @param mixed $number 要检查的值
  266. * @param int $decimals 允许的最大小数位数(默认 2)
  267. * @param string|null $sign 要求的符号:'positive' 大于 0 , 'negative' 小于0, 'zero' 等于0, 'non-negative' 大于或等于 0, 'non-positive' 小于或等于 0 null 表示不限制
  268. * @param bool $strict 是否严格模式(不允许整数传字符串等)
  269. * @return array ['valid' => bool, 'error' => string|null, 'info' => array]
  270. */
  271. public function checkNumber($number, $decimals = 2, $sign = null, $strict = false)
  272. {
  273. $result = [
  274. 'valid' => false,
  275. 'error' => null,
  276. 'info' => []
  277. ];
  278. // 1. 类型检查
  279. if ($strict) {
  280. if (!is_numeric($number) || is_bool($number)) {
  281. $result['error'] = '必须是数字类型';
  282. return $result;
  283. }
  284. } else {
  285. // 宽松模式:允许字符串数字
  286. if (!is_numeric($number)) {
  287. $result['error'] = '不是有效数字';
  288. return $result;
  289. }
  290. }
  291. $num = (float)$number; // 统一转为浮点数处理
  292. // 2. 正负号检查
  293. if ($sign !== null) {
  294. switch ($sign) {
  295. case 'positive':
  296. if ($num <= 0) {
  297. $result['error'] = '数字必须大于 0';
  298. return $result;
  299. }
  300. break;
  301. case 'negative':
  302. if ($num >= 0) {
  303. $result['error'] = '数字必须小于 0';
  304. return $result;
  305. }
  306. break;
  307. case 'zero':
  308. if ($num != 0) {
  309. $result['error'] = '数字必须等于 0';
  310. return $result;
  311. }
  312. break;
  313. case 'non-negative': // 大于等于 0
  314. if ($num < 0) {
  315. $result['error'] = '数字必须大于或等于 0';
  316. return $result;
  317. }
  318. break;
  319. case 'non-positive': // 小于等于 0
  320. if ($num > 0) {
  321. $result['error'] = '数字必须小于或等于 0';
  322. return $result;
  323. }
  324. break;
  325. default:
  326. $result['error'] = "不支持的符号类型: '{$sign}'";
  327. return $result;
  328. }
  329. }
  330. // 3. 小数位数检查
  331. // 将数字转为标准格式,避免科学计数法
  332. $numStr = rtrim(rtrim(sprintf('%.10F', $num), '0'), '.'); // 去除末尾无意义的0
  333. if ($numStr === '' || $numStr === '-') {
  334. $numStr = '0';
  335. }
  336. // 检查是否有小数点
  337. if (strpos($numStr, '.') === false) {
  338. $decimalPlaces = 0;
  339. } else {
  340. $parts = explode('.', $numStr);
  341. $decimalPlaces = strlen($parts[1]);
  342. }
  343. if ($decimalPlaces > $decimals) {
  344. $result['error'] = "小数位数超过 {$decimals} 位(实际 {$decimalPlaces} 位)";
  345. return $result;
  346. }
  347. // 4. 附加信息
  348. $result['valid'] = true;
  349. $result['info'] = [
  350. 'original' => $number,
  351. 'value' => $num,
  352. 'decimal_places' => $decimalPlaces,
  353. 'sign' => $num > 0 ? 'positive' : ($num < 0 ? 'negative' : 'zero'),
  354. ];
  355. return $result;
  356. }
  357. function isValidPhone($phone) {
  358. 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);
  359. }
  360. }