PHP封装方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
/**
* 将表情进行转义 用于存储的时候
* @param [type] $str [description]
* @return [type] [description]
*/
function emoji_encode($str){
$strEncode = '';
$length = mb_strlen($str,'utf-8');
for ($i=0; $i < $length; $i++) {
$_tmpStr = mb_substr($str,$i,1,'utf-8');
if(strlen($_tmpStr) >= 4){
$strEncode .= '[[EMOJI:'.rawurlencode($_tmpStr).']]';
}else{
$strEncode .= $_tmpStr;
}
}
return $strEncode;
}

/**
* 将表情进行反转义 用于读取的时候
* @param [type] $str [description]
* @return [type] [description]
*/
function emoji_decode($str){
$strDecode = preg_replace_callback('|\[\[EMOJI:(.*?)\]\]|', function($matches){
return rawurldecode($matches[1]);
}, $str);
return $strDecode;
}

/**
* 根据时间戳比较,获取状态
* @param [type] $start_time 开始时间戳
* @param [type] $end_time 结束时间戳
* @param [type] $text 格式类型
* @return [type] [description]
*/
function getTimeStatus($start_time, $end_time, $type = 'text')
{
if($type == 'text') {
if(time() < $start_time && time() < $end_time) {
$str = "<span style='color: #0a6aa1;'>未开始</em>";
}else if(time() >= $start_time && time() < $end_time) {
$str = "<span style='color: #19be6b;'>进行中</em>";
}else {
$str = "<span style='color: #ff0000;'>已结束</em>";
}
}else {
if(time() < $start_time && time() < $end_time) {
$str = 0; //未开始
}else if(time() >= $start_time && time() < $end_time) {
$str = 1; //进行中
}else {
$str = 2; //已结束
}
}
return $str;
}

/**
* 返回时间段的日期、时间戳
* @param string $type 时间类型
* @param array $map ['pm'=>'-', 'n'=>1] pm:表示正或负, n:表示天数
* @param boolean $slot true返回时间段,否当天时间
* @return void
*/
function getTime($type = "", $map = ['pm'=>'-', 'n'=>1], $slot = false)
{
switch ($type) {
case 'day': //昨天、明天、近七天、近一个月、近半年、近一年...
$n = $map['n'] ? : 1;
if($map['pm'] == '+') {
$date = date("Y-m-d", strtotime("+{$n} day"));
if($slot) {
$start_time = time();
$end_time = strtotime("+{$n} day");
}else {
$start_time = strtotime($date);
$end_time = $start_time + + 60 * 60 * 24 - 1;
}
}else {
$date = date("Y-m-d", strtotime("-{$n} day"));
$start_time = strtotime($date);
$end_time = $slot ? time() : ($start_time + 60 * 60 * 24 - 1);
}
$arr = [
'start_time' => $start_time,
'start_date' => date("Y-m-d H:i:s", $start_time),
'end_time' => $end_time,
'end_date' => date("Y-m-d H:i:s", $end_time),
];
break;
default: //今日
$start_time = strtotime(date("Y-m-d", time()));
$end_time = $start_time + 60 * 60 * 24 - 1;
$arr = [
'start_time' => $start_time,
'start_date' => date("Y-m-d H:i:s", $start_time),
'end_time' => $end_time,
'end_date' => date("Y-m-d H:i:s", $end_time),
];
break;
}
return $arr;
}

/**
* 根据时间戳转年月日
* @param $time 时间戳
* @return string
*/
function time_tran($time)
{
$t = time() - $time;
$f = [
'31536000' => '年',
'2592000' => '个月',
'604800' => '星期',
'86400' => '天',
'3600' => '小时',
'60' => '分钟',
'1' => '秒'
];
foreach ($f as $k => $v) {
if (0 != $c = floor($t / (int)$k)) {
return $c . $v . '前';
}
}
}

/**
* 时间 H:i:s 转 s
* @User yaokai
* @param $his
* @return float|int
*/
function HisToS($his)
{
$str = explode(':', $his);
$len = count($str);
if ($len == 3) {
$time = $str[0] * 3600 + $str[1] * 60 + $str[2];
} elseif ($len == 2) {
$time = $str[0] * 60 + $str[1];
} elseif ($len == 1) {
$time = $str[0];
} else {
$time = 0;
}
return $time;
}

/**
* 把秒数转换为时分秒(00:00:00)或分秒(00:00)的格式
* @param Int $times 时间,单位(秒)
* @param Int $type 1-时分秒 2-分秒
* @return String
*/
function secondToTime($times,$type = 1){
if($type == 1){
$result = '00:00:00';
if ($times>0) {
$hour = floor($times/3600);
$minute = floor(($times-3600 * $hour)/60);
$second = floor((($times-3600 * $hour) - 60 * $minute) % 60);
$hour = $hour < 10 ? '0'.$hour : $hour;
$minute = $minute < 10 ? '0'.$minute : $minute;
$second = $second < 10 ? '0'.$second : $second;
$result = $hour.':'.$minute.':'.$second;
}
}else{
$result = '00:00';
if ($times>0) {
$hour = floor($times/3600);
$minute = floor(($times-3600 * $hour)/60);
$second = floor((($times-3600 * $hour) - 60 * $minute) % 60);
$hour = $hour < 10 ? '0'.$hour : $hour;
$minute = $hour*60 + $minute;
$minute = $minute < 10 ? '0'.$minute : $minute;
$second = $second < 10 ? '0'.$second : $second;
$result = $minute.':'.$second;
}
}
return $result;
}

/**
* 获取指定年月日的开始时间戳和结束时间戳(本地时间戳非GMT时间戳)
* [1] 指定年:获取指定年份第一天第一秒的时间戳和下一年第一天第一秒的时间戳
* [2] 指定年月:获取指定年月第一天第一秒的时间戳和下一月第一天第一秒时间戳
* [3] 指定年月日:获取指定年月日第一天第一秒的时间戳
* @param integer $year [年份]
* @param integer $month [月份]
* @param integer $day [日期]
* @return array('start' => '', 'end' => '')
*/
function getStartAndEndUnixTimestamp($year = 0, $month = 0, $day = 0)
{
if(empty($year))
{
$year = date("Y");
}

$start_year = $year;
$start_year_formated = str_pad(intval($start_year), 4, "0", STR_PAD_RIGHT);
$end_year = $start_year + 1;
$end_year_formated = str_pad(intval($end_year), 4, "0", STR_PAD_RIGHT);

if(empty($month))
{
//只设置了年份
$start_month_formated = '01';
$end_month_formated = '01';
$start_day_formated = '01';
$end_day_formated = '01';
}
else
{
$month > 12 || $month < 1 ? $month = 1 : $month = $month;
$start_month = $month;
$start_month_formated = sprintf("%02d", intval($start_month));

if(empty($day))
{
//只设置了年份和月份
$end_month = $start_month + 1;

if($end_month > 12)
{
$end_month = 1;
}
else
{
$end_year_formated = $start_year_formated;
}
$end_month_formated = sprintf("%02d", intval($end_month));
$start_day_formated = '01';
$end_day_formated = '01';
}
else
{
//设置了年份月份和日期
$startTimestamp = strtotime($start_year_formated.'-'.$start_month_formated.'-'.sprintf("%02d", intval($day))." 00:00:00");
$endTimestamp = $startTimestamp + 24 * 3600 - 1;
return array('start' => $startTimestamp, 'end' => $endTimestamp);
}
}

$startTimestamp = strtotime($start_year_formated.'-'.$start_month_formated.'-'.$start_day_formated." 00:00:00");
$endTimestamp = strtotime($end_year_formated.'-'.$end_month_formated.'-'.$end_day_formated." 00:00:00") - 1;
return array('start' => $startTimestamp, 'end' => $endTimestamp);
}

/**
* 匿名处理
* @param string $data 数据
* @param string $type 类型
* @param int $start 开始显示位数,自定义填
* @param int $end 结束显示位数,自定义填
* @param string $symbol 符号
* @return [type] [description]
*/
function anonymity($data, $type = "", $start = 1, $end = 0, $symbol = '*')
{
if(!$data) return '';
switch ($type) {
case 'mobile':
return substr_replace($data, '****', 3, 4);
break;
case 'name'://姓名加密
if(preg_match("/[\x{4e00}-\x{9fa5}]+/u", $data)) {//判断是否包含中文字符
//按照中文字符计算长度
$len = mb_strlen($data, 'UTF-8');
if($len >= 3){//三个字符或三个字符以上掐头取尾,中间用*代替
return mb_substr($data, 0, 1, 'UTF-8') . str_repeat($symbol, $len-2) . mb_substr($data, -1, 1, 'UTF-8');
} elseif($len === 2) {//两个字符
return mb_substr($data, 0, 1, 'UTF-8') . $symbol;
}
} else {
//按照英文字串计算长度
$len = strlen($data);
if($len >= 3) {//三个字符或三个字符以上掐头取尾,中间用*代替
return substr($data, 0, 1) . str_repeat($symbol, $len-2) . substr($data, -1);
} elseif($len === 2) {//两个字符
return substr($data, 0, 1) . $symbol;
}
}
break;
default://自定义加密
$len = mb_strlen($data,'UTF-8') - $start - $end;
if($len > 0){
$str = str_repeat($symbol,$len);//替换字符数量
if(preg_match("/[\x{4e00}-\x{9fa5}]+/u", $data)) {//含有中文
return mb_substr($data, 0, $start, 'UTF-8') . $str . mb_substr($data, $start + $len , $end, 'UTF-8');
} else {
return substr_replace($data, $str, $start, $len);
}
} elseif($len == 0){
return mb_substr($data, 0, 1, 'UTF-8') . str_repeat($symbol, mb_strlen($data,'UTF-8') - 1) . mb_substr($data, -1, 1, 'UTF-8');
} else{
return $data . $symbol;
}
break;
}
}

/**
* 生成随机数
* $type: 1:纯数字 2: 纯小写字母 ,否则结合
* $length: 指定生成数量
*/
function rand_code($length, $type = ''){
switch ($type) {
case 1:
$chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
break;
case 2:
$chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y','z'];
break;
default:
$chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z'];
break;
}
$keys = array_rand($chars, $length);
$str = '';
for($i = 0; $i < $length; $i++){
$str .= $chars[$keys[$i]];
}
return $str;
}

/**
* 检查密码复杂度
* @param $pwd 密码
* @param int $pwdLen 密码长度,默认6位
* @return array
*/
function checkPassword($pwd, $pwdLen = 6) {
if ($pwd == null) {
return ['code' => 500, 'msg' => '密码不能为空'];
}
$pwd = trim($pwd);
if (preg_match('/[\x{4e00}-\x{9fa5}]/u', $pwd) > 0) {
return ['code' => 500, 'msg' => '密码不能包含中文'];
}
if (strlen($pwd) < $pwdLen) {
return ['code'=>500,'msg'=>'密码必须大于'.$pwdLen.'个字符'];
}
if (preg_match_all('/[0-9]/', $pwd, $o) < 1) {
return ['code'=>500,'msg'=>'密码必须包含至少一个数字'];
}
if (preg_match_all('/[a-z]/', $pwd, $o) < 1) {
return ['code'=>500,'msg'=>'密码必须包含至少一个小写字母'];
}
if (preg_match_all('/[A-Z]/', $pwd, $o) < 1) {
return ['code'=>500,'msg'=>'密码必须包含至少一个大写字母'];
}
if (preg_match_all('/[!@#$%^&*]/', $pwd, $o) < 1) {
return ['code'=>500,'msg'=>'密码必须包含至少一个特殊符号 !@#$%^&*'];
}
return ['code' => 200, 'msg' => '密码复杂度通过验证'];
}

/**
* 二维数组根据某字段排序
* @param array $data 二维数组
* @param string $field 字段
* @param integer $type 排序 1:SORT_DESC 降序, 0:SORT_ASC 升序
* @return [type] [description]
*/
function arrSort($data = [], $field = "id", $type = 0)
{
if(empty($data)) return $data;
$sort = [
'direction' => $type == 1 ? 'SORT_DESC' : 'SORT_ASC',
'field' => $field, //排序字段
];
$arr = [];
foreach($data AS $k => $v){
foreach($v AS $key => $value){
$arr[$key][$k] = $value;
}
}
array_multisort($arr[$sort['field']], constant($sort['direction']), $data);
return $data;
}


/**
* 二维数组(二维只有一个字段)转一维数字键数组
* @param $arr
* @param $field
* @return array
*/
function turnArr($data, $field = ''){
if(empty($data)) return $data;
$arr = [];
foreach($data as $k => $v){
if(empty($field) || count($v) == 1) {
$arr[$k] = array_shift($v);
}else {
$arr[$k] = $v[$field];
}
}
return $arr;
}

/**
* 富文本编辑器值替换
* @param [type] $detail [description]
* @return [type] [description]
*/
function xcx_detail($detail)
{
return str_replace(['/uploads/ueditor','&nbsp;'], [request()->domain().'/uploads/ueditor','&ensp;'], htmlspecialchars_decode($detail));
}

/**
* 把1000转换为1k,10000转换为1w
* @param $num
* @return mixed|string
*/
function convert($num)
{
if ($num >= 100000)
{
$num = round($num / 10000) .'W+';
}
else if ($num >= 10000)
{
$num = round($num / 10000, 1) .'W+';
}
else if($num >= 1000)
{
$num = round($num / 1000, 1) . 'K+';
}
return $num;
}

/**
* Guzzle请求 https://guzzle-cn.readthedocs.io/zh_CN/latest/
* @param $url 请求地址
* @param array $data 数据
* @param string $method 请求方法
* @param string $options 请求选项 [常用:GET=>query POST=>form_params POST=>json ] //https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html
* @param array $headers 请求头
* @return array
* @throws \GuzzleHttp\Exception\GuzzleException
*/
function guzzle_request($url, $data = [] , $method = "GET", $options = 'query' , $headers = [])
{
try {
$client = new \GuzzleHttp\Client();
array_unshift($headers,['content-type' => 'application/json;charset=utf-8']);
// $headers = ["content-type" => 'application/json;charset=utf-8'];

$parameter = [$options => $data, 'headers' => $headers];

$res = $client->request($method, $url, $parameter);

if ($res->getStatusCode() == 200) {
$callback = json_decode($res->getBody()->getContents(),true);
return ['code'=>200,'msg'=>'OK','data'=>$callback];
}else{
return ['code'=>500,'msg'=>'请求错误'];
}
} catch (\GuzzleHttp\Exception\RequestException $e) {
// dd($e->getRequest());dd($e->getResponse());
return ['code'=>500,'msg'=>'出现异常'];
}
}