1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace AlecRabbit; |
4
|
|
|
|
5
|
|
|
use const AlecRabbit\Helpers\Constants\EMPTY_ELEMENTS; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* @param array $data |
9
|
|
|
* @param int $columns |
10
|
|
|
* @param callable|null $callback |
11
|
|
|
* @param int $pad |
12
|
|
|
* @return array |
13
|
|
|
*/ |
14
|
|
|
function formatted_array( |
15
|
|
|
array $data, |
16
|
|
|
int $columns = 10, |
17
|
|
|
?callable $callback = null, |
18
|
|
|
int $pad = STR_PAD_RIGHT |
19
|
|
|
): array { |
20
|
22 |
|
$result = []; |
21
|
22 |
|
if ($callback) { |
22
|
3 |
|
\array_walk($data, $callback); |
23
|
|
|
} |
24
|
22 |
|
$maxLength = arr_el_max_length($data); |
25
|
21 |
|
$tmp = []; |
26
|
21 |
|
$rowEmpty = true; |
27
|
21 |
|
foreach ($data as $element) { |
28
|
20 |
|
$tmp[] = \str_pad((string)$element, $maxLength, ' ', $pad); |
29
|
20 |
|
$rowEmpty &= \in_array($element, EMPTY_ELEMENTS, true); |
30
|
20 |
|
if (\count($tmp) >= $columns) { |
31
|
14 |
|
$result[] = \implode($rowEmpty ? '' : ' ', $tmp); |
32
|
14 |
|
$rowEmpty = true; |
33
|
20 |
|
$tmp = []; |
34
|
|
|
} |
35
|
|
|
} |
36
|
21 |
|
if (!empty($tmp)) { |
37
|
12 |
|
$result[] = \implode($rowEmpty ? '' : ' ', $tmp); |
38
|
|
|
} |
39
|
21 |
|
return $result; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param array $data |
45
|
|
|
* @internal |
46
|
|
|
* @return int |
47
|
|
|
*/ |
48
|
|
|
function arr_el_max_length(array $data): int |
49
|
|
|
{ |
50
|
31 |
|
$maxLength = 0; |
51
|
31 |
|
foreach ($data as $element) { |
52
|
30 |
|
if (\is_array($element)) { |
53
|
1 |
|
throw new \RuntimeException('Array to string conversion'); |
54
|
|
|
} |
55
|
29 |
|
$len = \strlen((string)$element); |
56
|
29 |
|
if ($maxLength < $len) { |
57
|
29 |
|
$maxLength = $len; |
58
|
|
|
} |
59
|
|
|
} |
60
|
30 |
|
return $maxLength; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param array $data |
65
|
|
|
* @return array |
66
|
|
|
*/ |
67
|
|
|
function unset_first(array $data): array |
68
|
|
|
{ |
69
|
|
|
// TODO for PHP >=7.3 this line should use \array_key_first |
70
|
11 |
|
$key = array_key_first($data); |
71
|
11 |
|
if (null !== $key) { |
72
|
10 |
|
unset($data[$key]); |
73
|
|
|
} |
74
|
11 |
|
return $data; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @param array $data |
79
|
|
|
* @return int|null|string |
80
|
|
|
*/ |
81
|
|
|
function array_key_first(array $data) |
82
|
|
|
{ |
83
|
14 |
|
foreach ($data as $key => $value) { |
84
|
|
|
// this loop does not loop |
85
|
12 |
|
return $key; |
86
|
|
|
} |
87
|
2 |
|
} |
88
|
|
|
|
89
|
|
|
/** |
90
|
|
|
* @param array $data |
91
|
|
|
* @return int|null|string |
92
|
|
|
*/ |
93
|
|
|
function array_key_last(array $data) |
94
|
|
|
{ |
95
|
3 |
|
end($data); |
96
|
3 |
|
return key($data); |
97
|
|
|
} |
98
|
|
|
|