-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathArrayTrait.php
More file actions
105 lines (90 loc) · 2.55 KB
/
Copy pathArrayTrait.php
File metadata and controls
105 lines (90 loc) · 2.55 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
namespace WPMedia\PHPUnit;
trait ArrayTrait {
/**
* Flatten a multi-dimensional associative array with the delimiter.
*
* @param array $array Array to flatten.
* @param string $prepend Optional. String to prepend to key.
* @param bool $arrayOnly Optional. When true, only processes when value is an array.
*
* @return array flattened array
*/
public function flatten( array $array, $prepend = '', $arrayOnly = false, $delimiter = '/' ) {
$results = [];
foreach ( $array as $key => $value ) {
if ( $arrayOnly ) {
if ( ! is_array( $value ) ) {
continue;
}
$results[ "{$prepend}{$key}" ] = $value;
}
if ( ( $arrayOnly || is_array( $value ) ) && ! empty( $value ) ) {
$results = array_merge(
$results,
$this->flatten( $value, "{$prepend}{$key}{$delimiter}", $arrayOnly, $delimiter )
);
} elseif ( ! $arrayOnly ) {
$results[ "{$prepend}{$key}" ] = $value;
}
}
return $results;
}
/**
* Get an item from an array using delimiter notation.
*
* @param array $search Search array.
* @param string $keyToFind Key to find.
* @param mixed $default Optional. Default value to return if key does not exist in search array.
* @param string $delimiter Optional. The keys' delimiter, i.e. what separating the keys.
*
* @return mixed value returned.
*/
public function get( $search, $keyToFind, $default = null, $delimiter = '/' ) {
if ( ! is_array( $search ) ) {
return $default;
}
if ( is_null( $keyToFind ) ) {
return $search;
}
if ( array_key_exists( $keyToFind, $search ) ) {
return $search[ $keyToFind ];
}
foreach ( explode( $delimiter, $keyToFind ) as $segment ) {
if ( is_array( $search ) && array_key_exists( $segment, $search ) ) {
$search = $search[ $segment ];
} else {
return $default;
}
}
return $search;
}
/**
* Check if an item exists in an array using delimiter notation.
*
* @param array $search Search array.
* @param string $keyToFind Key to find.
* @param string $delimiter Optional. The keys' delimiter, i.e. what separates the keys.
*
* @return bool
*/
public function has( array $search, $keyToFind, $delimiter = '/' ) {
if ( empty( $search ) ) {
return false;
}
if ( is_null( $keyToFind ) ) {
return false;
}
if ( array_key_exists( $keyToFind, $search ) ) {
return true;
}
foreach ( explode( $delimiter, $keyToFind ) as $segment ) {
if ( array_key_exists( $segment, $search ) ) {
$search = $search[ $segment ];
} else {
return false;
}
}
return true;
}
}