1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ArrayHelpers; |
4
|
|
|
|
5
|
|
|
class Arr |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* Get an item from an array. |
9
|
|
|
* Supports dot notation: |
10
|
|
|
* e.g `Arr::get($array, 'section.subsection.item')` |
11
|
|
|
* |
12
|
|
|
* @param array $array |
13
|
|
|
* @param string $key |
14
|
|
|
* @param mixed|null $default |
15
|
|
|
* @return mixed|null |
16
|
|
|
*/ |
17
|
5 |
|
public static function get(array $array, $key, $default = null) |
18
|
|
|
{ |
19
|
5 |
|
if (array_key_exists($key, $array)) { |
20
|
2 |
|
return $array[$key]; |
21
|
|
|
} |
22
|
|
|
|
23
|
4 |
|
if (strpos($key, '.') === false) { |
24
|
2 |
|
return $default; |
25
|
|
|
} |
26
|
|
|
|
27
|
2 |
|
$keys = explode('.', $key); |
28
|
2 |
View Code Duplication |
while (count($keys) > 0) { |
|
|
|
|
29
|
2 |
|
$shiftedKey = array_shift($keys); |
30
|
2 |
|
if (!array_key_exists($shiftedKey, $array)) { |
31
|
1 |
|
return $default; |
32
|
|
|
} |
33
|
1 |
|
return static::get($array[$shiftedKey], join('.', $keys), $default); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
return $default; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Checks if an item is available in an array. |
41
|
|
|
* Supports dot notation: |
42
|
|
|
* e.g `Arr::has($array, 'section.subsection.item')` |
43
|
|
|
* |
44
|
|
|
* @param array $array |
45
|
|
|
* @param string $key |
46
|
|
|
* @return bool |
47
|
|
|
*/ |
48
|
4 |
|
public static function has(array $array, $key) |
49
|
|
|
{ |
50
|
4 |
|
if (array_key_exists($key, $array)) { |
51
|
2 |
|
return true; |
52
|
|
|
} |
53
|
|
|
|
54
|
3 |
|
if (strpos($key, '.') === false) { |
55
|
1 |
|
return false; |
56
|
|
|
} |
57
|
|
|
|
58
|
2 |
|
$keys = explode('.', $key); |
59
|
2 |
View Code Duplication |
while (count($keys) > 0) { |
|
|
|
|
60
|
2 |
|
$shiftedKey = array_shift($keys); |
61
|
2 |
|
if (!array_key_exists($shiftedKey, $array)) { |
62
|
1 |
|
return false; |
63
|
|
|
} |
64
|
1 |
|
return static::has($array[$shiftedKey], join('.', $keys)); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return false; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.