-
-
Notifications
You must be signed in to change notification settings - Fork 312
/
Arr.php
84 lines (70 loc) · 1.92 KB
/
Arr.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
declare(strict_types=1);
namespace Pest\Support;
/**
* @internal
*/
final class Arr
{
/**
* Checks if the given array has the given key.
*
* @param array<array-key, mixed> $array
*/
public static function has(array $array, string|int $key): bool
{
$key = (string) $key;
if (array_key_exists($key, $array)) {
return true;
}
foreach (explode('.', $key) as $segment) {
if (is_array($array) && array_key_exists($segment, $array)) {
$array = $array[$segment];
} else {
return false;
}
}
return true;
}
/**
* Gets the given key value.
*
* @param array<array-key, mixed> $array
*/
public static function get(array $array, string|int $key, mixed $default = null): mixed
{
$key = (string) $key;
if (array_key_exists($key, $array)) {
return $array[$key];
}
if (! str_contains($key, '.')) {
return $array[$key] ?? $default;
}
foreach (explode('.', $key) as $segment) {
if (is_array($array) && array_key_exists($segment, $array)) {
$array = $array[$segment];
} else {
return $default;
}
}
return $array;
}
/**
* Flatten a multi-dimensional associative array with dots.
*
* @param array<array-key, mixed> $array
* @return array<int|string, mixed>
*/
public static function dot(array $array, string $prepend = ''): array
{
$results = [];
foreach ($array as $key => $value) {
if (is_array($value) && $value !== []) {
$results = array_merge($results, self::dot($value, $prepend.$key.'.'));
} else {
$results[$prepend.$value] = $value;
}
}
return $results;
}
}