Completed
Push — master ( 8f1053...c250e4 )
by Antonio
13:19
created

ArrayHelper::getValue()   D

Complexity

Conditions 10
Paths 19

Size

Total Lines 27
Code Lines 19

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 27
rs 4.8197
cc 10
eloc 19
nc 19
nop 3

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace Da\Mailer\Helper;
3
4
use Closure;
5
6
class ArrayHelper
7
{
8
    /**
9
     * Retrieves the value of an array element or object property with the given key or property name.
10
     * If the key does not exist in the array or object, the default value will be returned instead.
11
     *
12
     * The key may be specified in a dot format to retrieve the value of a sub-array or the property
13
     * of an embedded object. In particular, if the key is `x.y.z`, then the returned value would
14
     * be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']`
15
     * or `$array->x` is neither an array nor an object, the default value will be returned.
16
     * Note that if the array already has an element `x.y.z`, then its value will be returned
17
     * instead of going through the sub-arrays. So it is better to be done specifying an array of key names
18
     * like `['x', 'y', 'z']`.
19
     *
20
     * Below are some usage examples,
21
     *
22
     * ~~~
23
     * // working with array
24
     * $username = ArrayHelper::getValue($_POST, 'username');
25
     * // working with object
26
     * $username = ArrayHelper::getValue($user, 'username');
27
     * // working with anonymous function
28
     * $fullName = ArrayHelper::getValue($user, function ($user, $defaultValue) {
29
     *     return $user->firstName . ' ' . $user->lastName;
30
     * });
31
     * // using dot format to retrieve the property of embedded object
32
     * $street = ArrayHelper::getValue($users, 'address.street');
33
     * // using an array of keys to retrieve the value
34
     * $value = ArrayHelper::getValue($versions, ['1.0', 'date']);
35
     * ~~~
36
     *
37
     * @param array|object $array array or object to extract value from
38
     * @param string|\Closure|array $key key name of the array element, an array of keys or property name of the object,
39
     * or an anonymous function returning the value. The anonymous function signature should be:
40
     * `function($array, $defaultValue)`.
41
     * @param mixed $default the default value to be returned if the specified array key does not exist. Not used when
42
     * getting value from an object.
43
     *
44
     * @return mixed the value of the element if found, default value otherwise
45
     */
46
    public static function getValue($array, $key, $default = null)
47
    {
48
        if ($key instanceof Closure) {
49
            return $key($array, $default);
50
        }
51
        if (is_array($key)) {
52
            $lastKey = array_pop($key);
53
            foreach ($key as $keyPart) {
54
                $array = static::getValue($array, $keyPart);
55
            }
56
            $key = $lastKey;
57
        }
58
        if (is_array($array) && array_key_exists($key, $array)) {
59
            return $array[$key];
60
        }
61
        if (($pos = strrpos($key, '.')) !== false) {
62
            $array = static::getValue($array, substr($key, 0, $pos), $default);
63
            $key = substr($key, $pos + 1);
64
        }
65
        if (is_object($array)) {
66
            return $array->$key;
67
        } elseif (is_array($array)) {
68
            return array_key_exists($key, $array) ? $array[$key] : $default;
69
        } else {
70
            return $default;
71
        }
72
    }
73
74
    /**
75
     * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
76
     * will be returned instead.
77
     *
78
     * Usage examples,
79
     *
80
     * ~~~
81
     * // $array = ['type' => 'A', 'options' => [1, 2]];
82
     * // working with array
83
     *  $type = ArrayHelper::remove($array, 'type');
84
     * // $array content
85
     * // $array = ['options' => [1, 2]];
86
     * ~~~
87
     *
88
     * @param array $array the array to extract value from
89
     * @param string $key key name of the array element
90
     * @param mixed $default the default value to be returned if the specified key does not exist
91
     *
92
     * @return mixed|null the value of the element if found, default value otherwise
93
     */
94
    public static function remove(&$array, $key, $default = null)
95
    {
96
        if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) {
97
            $value = $array[$key];
98
            unset($array[$key]);
99
100
            return $value;
101
        }
102
103
        return $default;
104
    }
105
}
106