Passed
Push — feature/optimize ( 06281d )
by Fu
03:39
created

ascii_encode()   C

Complexity

Conditions 16
Paths 9

Size

Total Lines 47
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 43
dl 0
loc 47
rs 5.5666
c 1
b 0
f 0
cc 16
nc 9
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: frowhy
5
 * Date: 2017/11/26
6
 * Time: 下午2:45
7
 */
8
9
use Carbon\Carbon;
10
use Illuminate\Support\Arr;
11
use Illuminate\Support\Collection;
12
use Illuminate\Support\Str;
13
14
/**
15
 * 生成验证码
16
 */
17
if (!function_exists('verification_code')) {
18
    function verification_code(int $length = 4, string $type = 'int'): string
19
    {
20
        if ('int' === $type) {
21
            return sprintf("%0{$length}d", rand(0, pow(10, $length) - 1));
22
        } else {
23
            return Str::random($length);
24
        }
25
    }
26
}
27
28
/**
29
 * 相对 URL
30
 */
31
if (!function_exists('relative_url')) {
32
    function relative_url(?string $url = null): ?string
33
    {
34
        return $url === null
35
            ? $url
36
            : (false === Str::startsWith($url, 'http://') ? (false === Str::startsWith($url, 'https://')
37
                ? $url : Str::replaceFirst('https://', '//', $url)) : Str::replaceFirst('http://', '//', $url));
38
    }
39
}
40
41
/**
42
 * 储存 URL
43
 */
44
if (!function_exists('storage_url')) {
45
    function storage_url(?string $url = null): ?string
46
    {
47
        return $url === null ? $url : (Str::startsWith($url, 'http') ? $url : Storage::url($url));
48
    }
49
}
50
51
/**
52
 * 两位小数
53
 */
54
if (!function_exists('price')) {
55
    function price(float $price): string
56
    {
57
        return number_format($price, 2);
58
    }
59
}
60
61
/**
62
 * 16 进制转 RGB
63
 */
64
if (!function_exists('hex2rgb')) {
65
    function hex2rgb(string $hexColor): array
66
    {
67
        $color = str_replace('#', '', $hexColor);
68
        if (strlen($color) > 3) {
69
            $rgb = [
70
                'r' => hexdec(substr($color, 0, 2)),
71
                'g' => hexdec(substr($color, 2, 2)),
72
                'b' => hexdec(substr($color, 4, 2)),
73
            ];
74
        } else {
75
            $color = $hexColor;
76
            $r = substr($color, 0, 1).substr($color, 0, 1);
77
            $g = substr($color, 1, 1).substr($color, 1, 1);
78
            $b = substr($color, 2, 1).substr($color, 2, 1);
79
            $rgb = [
80
                'r' => hexdec($r),
81
                'g' => hexdec($g),
82
                'b' => hexdec($b),
83
            ];
84
        }
85
86
        return $rgb;
87
    }
88
}
89
90
/**
91
 * 灰度等级
92
 */
93
if (!function_exists('gray_level')) {
94
    function gray_level(array $rgb): float
95
    {
96
        return $rgb['r'] * 0.299 + $rgb['g'] * 0.587 + $rgb['b'] * 0.114;
97
    }
98
}
99
100
/**
101
 * 去年时间范围
102
 */
103
if (!function_exists('last_year')) {
104
    function last_year(): array
105
    {
106
        $carbon = new Carbon();
107
        $start_at = $carbon->today()->subYear()->startOfYear();
108
        $end_at = $carbon->today()->subYear()->endOfYear();
109
110
        return compact('start_at', 'end_at');
111
    }
112
}
113
114
/**
115
 * 今年时间范围
116
 */
117
if (!function_exists('this_year')) {
118
    function this_year(): array
119
    {
120
        $carbon = new Carbon();
121
        $start_at = $carbon->today()->startOfYear();
122
        $end_at = $carbon->today()->endOfYear();
123
124
        return compact('start_at', 'end_at');
125
    }
126
}
127
128
/**
129
 * 明年时间范围
130
 */
131
if (!function_exists('next_year')) {
132
    function next_year(): array
133
    {
134
        $carbon = new Carbon();
135
        $start_at = $carbon->today()->addYear()->startOfYear();
136
        $end_at = $carbon->today()->addYear()->endOfYear();
137
138
        return compact('start_at', 'end_at');
139
    }
140
}
141
142
/**
143
 * 上个月时间范围
144
 */
145
if (!function_exists('last_month')) {
146
    function last_month(): array
147
    {
148
        $carbon = new Carbon();
149
        $start_at = $carbon->today()->subMonth()->startOfMonth();
150
        $end_at = $carbon->today()->subMonth()->endOfMonth();
151
152
        return compact('start_at', 'end_at');
153
    }
154
}
155
156
/**
157
 * 本月时间范围
158
 */
159
if (!function_exists('this_month')) {
160
    function this_month(): array
161
    {
162
        $carbon = new Carbon();
163
        $start_at = $carbon->today()->startOfMonth();
164
        $end_at = $carbon->today()->endOfMonth();
165
166
        return compact('start_at', 'end_at');
167
    }
168
}
169
170
/**
171
 * 下个月时间范围
172
 */
173
if (!function_exists('next_month')) {
174
    function next_month(): array
175
    {
176
        $carbon = new Carbon();
177
        $start_at = $carbon->today()->addMonth()->startOfMonth();
178
        $end_at = $carbon->today()->addMonth()->endOfMonth();
179
180
        return compact('start_at', 'end_at');
181
    }
182
}
183
184
/**
185
 * 上周时间范围
186
 */
187
if (!function_exists('last_week')) {
188
    function last_week(): array
189
    {
190
        $carbon = new Carbon();
191
        $start_at = $carbon->today()->subWeek()->startOfWeek();
192
        $end_at = $carbon->today()->subWeek()->endOfWeek();
193
194
        return compact('start_at', 'end_at');
195
    }
196
}
197
198
/**
199
 * 本周时间范围
200
 */
201
if (!function_exists('this_week')) {
202
    function this_week(): array
203
    {
204
        $carbon = new Carbon();
205
        $start_at = $carbon->today()->startOfWeek();
206
        $end_at = $carbon->today()->endOfWeek();
207
208
        return compact('start_at', 'end_at');
209
    }
210
}
211
212
/**
213
 * 下周时间范围
214
 */
215
if (!function_exists('next_week')) {
216
    function next_week(): array
217
    {
218
        $carbon = new Carbon();
219
        $start_at = $carbon->today()->addWeek()->startOfWeek();
220
        $end_at = $carbon->today()->addWeek()->endOfWeek();
221
222
        return compact('start_at', 'end_at');
223
    }
224
}
225
226
/**
227
 * 昨天时间范围
228
 */
229
if (!function_exists('yesterday')) {
230
    function yesterday(): array
231
    {
232
        $carbon = new Carbon();
233
        $start_at = $carbon->yesterday()->startOfDay();
234
        $end_at = $carbon->yesterday()->startOfDay();
235
236
        return compact('start_at', 'end_at');
237
    }
238
}
239
240
/**
241
 * 今天时间范围
242
 */
243
if (!function_exists('today')) {
244
    function today(): array
245
    {
246
        $carbon = new Carbon();
247
        $start_at = $carbon->today()->startOfDay();
248
        $end_at = $carbon->today()->startOfDay();
249
250
        return compact('start_at', 'end_at');
251
    }
252
}
253
254
/**
255
 * 明天时间范围
256
 */
257
if (!function_exists('tomorrow')) {
258
    function tomorrow(): array
259
    {
260
        $carbon = new Carbon();
261
        $start_at = $carbon->tomorrow()->startOfDay();
262
        $end_at = $carbon->tomorrow()->startOfDay();
263
264
        return compact('start_at', 'end_at');
265
    }
266
}
267
268
/**
269
 * 微信浏览器
270
 */
271
if (!function_exists('in_wechat')) {
272
    function in_wechat(): bool
273
    {
274
        return Str::contains(request(), 'MicroMessenger');
275
    }
276
}
277
278
/**
279
 * 微信
280
 */
281
if (!function_exists('is_wechat')) {
282
    function is_wechat(): bool
283
    {
284
        return in_wechat() && !is_mini_program();
285
    }
286
}
287
288
/**
289
 * 小程序
290
 */
291
if (!function_exists('is_mini_program')) {
292
    function is_mini_program(): bool
293
    {
294
        return in_wechat() && request()->get('is_mini_program', false);
295
    }
296
}
297
298
/**
299
 * 读取 DATA 数据
300
 */
301
if (!function_exists('get_data')) {
302
    function get_data($data, $index = null, $key = null)
303
    {
304
        if ($data instanceof Collection || $data instanceof Modules\Core\Supports\Response) {
305
            $data = $data->toArray();
306
        }
307
308
        $field = Arr::has($data, 'data') ? 'data.' : '';
309
310
        if (Arr::has($data, "{$field}0") && !Arr::has($data, "{$field}1")) {
311
            if (!is_null($index) && is_int($index)) {
312
                $key = "{$index}.{$key}";
313
            } else {
314
                $key = is_null($index) ? 0 : "0.{$index}";
315
            }
316
        } else {
317
            $key = is_null($index) ? '' : $index;
318
        }
319
320
        $key = rtrim("{$field}{$key}", '.');
321
322
        return $key ? Arr::get($data, $key) : $data;
323
    }
324
}
325
326
/**
327
 * 清空缓存
328
 */
329
if (!function_exists('clear_cache')) {
330
    function clear_cache(): void
331
    {
332
        Cache::tags('website')->flush();
333
    }
334
}
335
336
/**
337
 * 判定缓存
338
 */
339
if (!function_exists('has_cache')) {
340
    function has_cache(string $uri): bool
341
    {
342
        return Cache::tags('website')->has($uri);
343
    }
344
}
345
346
/**
347
 * 读取缓存
348
 */
349
if (!function_exists('get_cache')) {
350
    function get_cache(string $uri)
351
    {
352
        return Cache::tags('website')->get($uri);
353
    }
354
}
355
356
/**
357
 * 写缓存
358
 */
359
if (!function_exists('set_cache')) {
360
    function set_cache(string $uri, string $response): void
361
    {
362
        Cache::tags('website')->put($uri, $response, config('cache.timeout'));
363
    }
364
}
365
366
/**
367
 * 随机值
368
 */
369
if (!function_exists('random')) {
370
    function random(int $length = 4, string $type = 'digital'): string
371
    {
372
        if ('digital' === $type) {
373
            return random_digital($length);
374
        } elseif ('alphabet' === $type) {
375
            return random_alphabet($length);
376
        } else {
377
            return Str::random($length);
378
        }
379
    }
380
}
381
382
/**
383
 * 随机数字
384
 */
385
if (!function_exists('random_digital')) {
386
    function random_digital(int $length = 4): string
387
    {
388
        return sprintf("%0{$length}d", rand(0, pow(10, $length) - 1));
389
    }
390
}
391
392
/**
393
 * 随机字母
394
 */
395
if (!function_exists('random_alphabet')) {
396
    function random_alphabet(int $length = 4): string
397
    {
398
        $str = '';
399
        $map = [
400
            ['65', '90'],
401
            ['97', '122'],
402
        ];
403
        for ($i = 0; $i < $length; $i++) {
404
            $param = Arr::random($map);
405
            $str .= chr(call_user_func_array('rand', $param));
406
        }
407
        return $str;
408
    }
409
}
410
411
/**
412
 * 随机大写字母
413
 */
414
if (!function_exists('random_alphabet_upper')) {
415
    function random_alphabet_upper(int $length = 4): string
416
    {
417
        return strtoupper(random_alphabet($length));
418
    }
419
}
420
421
/**
422
 * 随机小写字母
423
 */
424
if (!function_exists('random_alphabet_lower')) {
425
    function random_alphabet_lower(int $length = 4): string
426
    {
427
        return strtolower(random_alphabet($length));
428
    }
429
}
430
431
/**
432
 * 随机日期
433
 */
434
if (!function_exists('random_date')) {
435
    function random_date(): string
436
    {
437
        return (string) mt_rand(2000, (int) date('Y')).sprintf("%02d", mt_rand(1, 12)).sprintf("%02d", mt_rand(1, 28));
438
    }
439
}
440
441
/**
442
 * 轮询调度
443
 */
444
if (!function_exists('round_robin')) {
445
    function round_robin(array &$items, array &$result): void
446
    {
447
        $total = 0;
448
        $best = null;
449
450
        foreach ($items as $key => $item) {
451
            $current = &$items[$key];
452
            $weight = $current['weight'];
453
454
            $current['current_weight'] += $weight;
455
            $total += $weight;
456
457
            if (($best == null) || ($items[$best]['current_weight'] <
458
                                    $current['current_weight'])) {
459
                $best = $key;
460
            }
461
        }
462
463
        $items[$best]['current_weight'] -= $total;
464
        $items[$best]['count']++;
465
466
        $result[] = $best;
467
    }
468
}
469
470
/**
471
 * 13 位时间戳
472
 *
473
 * @return float
474
 */
475
if (!function_exists('get_millisecond')) {
476
    function get_millisecond(): float
477
    {
478
        list($t1, $t2) = explode(' ', microtime());
479
        return (float) sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
480
    }
481
}
482
483
/**
484
 * Get the boolean value of a variable
485
 */
486
if (!function_exists('is_true')) {
487
    function is_true($val): bool
488
    {
489
        return $val instanceof \Modules\Core\Contracts\Support\Boolable
490
            ? $val->toBool()
491
            : (is_string($val)
492
                ? filter_var($val, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) : boolval($val));
493
    }
494
}
495
496
if (!function_exists('get_routes')) {
497
    function get_routes($module = null): Collection
498
    {
499
        /** @var \Illuminate\Support\Collection $routes */
500
        $routes = collect(Route::getRoutes()->getRoutesByName())->groupBy(function ($item, $key) {
501
            $keys = explode('.', $key);
502
503
            return $keys[0];
504
        }, true)->map(function (Collection $item) {
505
            return $item->mapWithKeys(function ($item, $key) {
506
                $keys = explode('.', $key);
507
                $route = collect($item->action)
508
                    ->put('method', $item->methods[0])
509
                    ->put('uri', $item->uri)
510
                    ->forget('uses')
511
                    ->sort();
512
513
                return [implode('.', Arr::except($keys, 0)) => $route];
514
            })->sortKeys();
515
        })->sortKeys();
516
517
        if (null !== $module) {
518
            return $routes->get($module) ?? collect();
519
        }
520
521
        return $routes;
522
    }
523
}
524