1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Rde; |
4
|
|
|
|
5
|
|
|
// array |
6
|
|
|
// 效能先決,不做多餘檢查 |
7
|
|
|
|
8
|
|
|
function is_array($arg) |
9
|
|
|
{ |
10
|
1 |
|
return \is_array($arg) || \is_a($arg, 'ArrayAccess'); |
11
|
|
|
} |
12
|
|
|
|
13
|
|
|
function array_get($arr, $key, $default = null) |
14
|
|
|
{ |
15
|
1 |
|
if (array_key_exists($key, $arr)) { |
16
|
1 |
|
return $arr[$key]; |
17
|
|
|
} |
18
|
|
|
|
19
|
1 |
|
return value($default); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
// 參數順序同 array_map |
23
|
|
|
// callback 傳入參數順序 $key, $val |
24
|
|
|
function array_each($callback) |
25
|
|
|
{ |
26
|
1 |
|
foreach (array_slice(func_get_args(), 1) as $i => $arr) { |
27
|
1 |
|
foreach ($arr as $k => $v) { |
28
|
1 |
|
if (false === $callback($k, $v)) { |
29
|
|
|
break; |
30
|
|
|
} |
31
|
1 |
|
} |
32
|
1 |
|
} |
33
|
1 |
|
} |
34
|
|
|
|
35
|
|
|
function array_first($arr, $callback, $default = null) |
36
|
|
|
{ |
37
|
1 |
|
foreach ($arr as $k => $v) { |
38
|
1 |
|
if ($callback($k, $v)) { |
39
|
1 |
|
return $v; |
40
|
|
|
} |
41
|
1 |
|
} |
42
|
|
|
|
43
|
1 |
|
return value($default); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
function array_merge_callback($driver, array $base) |
47
|
|
|
{ |
48
|
4 |
|
$collection = $base; |
49
|
4 |
|
$appends = array_slice(func_get_args(), 2); |
50
|
|
|
|
51
|
4 |
|
foreach ($appends as $append) { |
52
|
4 |
|
foreach ($append as $k => $v) { |
53
|
4 |
|
$driver( |
54
|
4 |
|
$v, |
55
|
4 |
|
$k, |
56
|
4 |
|
$collection, |
57
|
4 |
|
$driver); |
58
|
4 |
|
} |
59
|
4 |
|
} |
60
|
|
|
|
61
|
4 |
|
return $collection; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
// tool |
65
|
|
|
function call($callable, array $args = array()) |
66
|
|
|
{ |
67
|
1 |
|
switch (count($args)) { |
68
|
1 |
|
case 0: return call_user_func($callable); |
69
|
1 |
|
case 1: return call_user_func($callable, $args[0]); |
70
|
1 |
|
case 2: return call_user_func($callable, $args[0], $args[1]); |
71
|
1 |
|
case 3: return call_user_func($callable, $args[0], $args[1], $args[2]); |
72
|
1 |
|
case 4: return call_user_func($callable, $args[0], $args[1], $args[2], $args[3]); |
73
|
1 |
|
} |
74
|
|
|
|
75
|
1 |
|
return call_user_func_array($callable, $args); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
function value($val) |
79
|
|
|
{ |
80
|
3 |
|
return $val instanceof \Closure ? $val() : $val; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
function with($any) |
84
|
|
|
{ |
85
|
|
|
return $any; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
// debug |
89
|
|
|
function dd() |
90
|
|
|
{ |
91
|
|
|
call_user_func_array('var_dump', func_get_args()); |
92
|
|
|
die; |
|
|
|
|
93
|
|
|
} |
94
|
|
|
|
An exit expression should only be used in rare cases. For example, if you write a short command line script.
In most cases however, using an
exit
expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.