-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArrayDataFilterTrait.php
61 lines (55 loc) · 1.5 KB
/
ArrayDataFilterTrait.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
<?php
/*
* This file is part of the Koded package.
*
* (c) Mihail Binev <[email protected]>
*
* Please view the LICENSE distributed with this source code
* for the full copyright and license information.
*/
namespace Koded\Stdlib;
use function array_key_exists;
use function explode;
use function str_replace;
use function str_starts_with;
use function strtolower;
trait ArrayDataFilterTrait
{
public function filter(
iterable $data,
string $prefix,
bool $lowercase = true,
bool $trim = true): array
{
$filtered = [];
foreach ($data as $index => $value) {
if ($trim && '' !== $prefix && str_starts_with($index, $prefix)) {
$index = str_replace($prefix, '', $index);
}
$filtered[$lowercase ? strtolower($index) : $index] = $value;
}
return $filtered;
}
public function find(string $index, mixed $default = null): mixed
{
if (isset($this->data[$index])) {
return $this->data[$index];
}
$data = $this->data;
foreach (explode('.', $index) as $token) {
if (false === array_key_exists($token, $data)) {
return $default;
}
$data =& $data[$token];
}
return $data;
}
public function extract(array $indexes): array
{
$found = [];
foreach ($indexes as $index) {
$found[$index] = $this->data[$index] ?? null;
}
return $found;
}
}