Total Complexity | 10 |
Total Lines | 61 |
Duplicated Lines | 19.67 % |
Changes | 0 |
Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
1 | <?php |
||
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 | public static function get(array $array, $key, $default = null) |
||
18 | { |
||
19 | if (array_key_exists($key, $array)) { |
||
20 | return $array[$key]; |
||
21 | } |
||
22 | |||
23 | if (strpos($key, '.') === false) { |
||
24 | return $default; |
||
25 | } |
||
26 | |||
27 | $keys = explode('.', $key); |
||
28 | View Code Duplication | while (count($keys) > 0) { |
|
|
|||
29 | $subSet = $array[array_shift($keys)]; |
||
30 | if (is_array($subSet)) { |
||
31 | return static::get($subSet, join('.', $keys), $default); |
||
32 | } |
||
33 | } |
||
34 | |||
35 | return $default; |
||
36 | } |
||
37 | |||
38 | /** |
||
39 | * Checks if an item is available in an array. |
||
40 | * Supports dot notation: |
||
41 | * e.g `Arr::has($array, 'section.subsection.item')` |
||
42 | * |
||
43 | * @param array $array |
||
44 | * @param string $key |
||
45 | * @return bool |
||
46 | */ |
||
47 | public static function has(array $array, $key) |
||
66 | } |
||
67 | } |
||
68 |
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.