|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the Koded package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Mihail Binev <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* Please view the LICENSE distributed with this source code |
|
9
|
|
|
* for the full copyright and license information. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Koded\Stdlib; |
|
13
|
|
|
|
|
14
|
|
|
use function array_key_exists; |
|
15
|
|
|
use function explode; |
|
16
|
|
|
use function str_replace; |
|
17
|
|
|
use function str_starts_with; |
|
18
|
|
|
use function strtolower; |
|
19
|
|
|
|
|
20
|
|
|
trait ArrayDataFilterTrait |
|
21
|
|
|
{ |
|
22
|
12 |
|
public function filter( |
|
23
|
|
|
iterable $data, |
|
24
|
|
|
string $prefix, |
|
25
|
|
|
bool $lowercase = true, |
|
26
|
|
|
bool $trim = true): array |
|
27
|
|
|
{ |
|
28
|
12 |
|
$filtered = []; |
|
29
|
12 |
|
foreach ($data as $index => $value) { |
|
30
|
12 |
|
if ($trim && '' !== $prefix && str_starts_with($index, $prefix)) { |
|
31
|
6 |
|
$index = str_replace($prefix, '', $index); |
|
32
|
|
|
} |
|
33
|
12 |
|
$filtered[$lowercase ? strtolower($index) : $index] = $value; |
|
34
|
|
|
} |
|
35
|
12 |
|
return $filtered; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
11 |
|
public function find(string $index, mixed $default = null): mixed |
|
39
|
|
|
{ |
|
40
|
11 |
|
if (isset($this->data[$index])) { |
|
41
|
6 |
|
return $this->data[$index]; |
|
42
|
|
|
} |
|
43
|
10 |
|
$data = $this->data; |
|
44
|
10 |
|
foreach (explode('.', $index) as $token) { |
|
45
|
10 |
|
if (false === array_key_exists($token, $data)) { |
|
46
|
4 |
|
return $default; |
|
47
|
|
|
} |
|
48
|
10 |
|
$data =& $data[$token]; |
|
49
|
|
|
} |
|
50
|
10 |
|
return $data; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
1 |
|
public function extract(array $indexes): array |
|
54
|
|
|
{ |
|
55
|
1 |
|
$found = []; |
|
56
|
1 |
|
foreach ($indexes as $index) { |
|
57
|
1 |
|
$found[$index] = $this->data[$index] ?? null; |
|
58
|
|
|
} |
|
59
|
1 |
|
return $found; |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|