Passed
Pull Request — master (#479)
by Def
04:04 queued 02:00
created

ArrayHelper   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 107
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 18
eloc 28
c 2
b 0
f 0
dl 0
loc 107
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
C getValueByPath() 0 44 13
A keyExists() 0 9 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Helper;
6
7
use ArrayAccess;
8
use Closure;
9
10
/**
11
 * Short implementation of ArrayHelper from Yii2
12
 */
13
class ArrayHelper
14
{
15
    /**
16
     * Checks if the given array contains the specified key.
17
     * This method enhances the `array_key_exists()` function by supporting case-insensitive
18
     * key comparison.
19
     *
20
     * @param string $key the key to check
21
     * @param array|ArrayAccess $array the array with keys to check
22
     *
23
     * @return bool whether the array contains the specified key
24
     */
25
    public static function keyExists(string $key, ArrayAccess|array $array): bool
26
    {
27
        // Function `isset` checks key faster but skips `null`, `array_key_exists` handles this case
28
        // https://www.php.net/manual/en/function.array-key-exists.php#107786
29
        if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) {
30
            return true;
31
        }
32
        // Cannot use `array_has_key` on Objects for PHP 7.4+, therefore we need to check using [[ArrayAccess::offsetExists()]]
33
        return $array instanceof ArrayAccess && $array->offsetExists($key);
34
    }
35
36
    /**
37
     * Retrieves the value of an array element or object property with the given key or property name.
38
     * If the key does not exist in the array, the default value will be returned instead.
39
     * Not used when getting value from an object.
40
     *
41
     * The key may be specified in a dot format to retrieve the value of a sub-array or the property
42
     * of an embedded object. In particular, if the key is `x.y.z`, then the returned value would
43
     * be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']`
44
     * or `$array->x` is neither an array nor an object, the default value will be returned.
45
     * Note that if the array already has an element `x.y.z`, then its value will be returned
46
     * instead of going through the sub-arrays. So it is better to be done specifying an array of key names
47
     * like `['x', 'y', 'z']`.
48
     *
49
     * Below are some usage examples,
50
     *
51
     * ```php
52
     * // working with array
53
     * $username = ArrayHelper::getValueByPath($_POST, 'username');
54
     * // working with object
55
     * $username = ArrayHelper::getValueByPath($user, 'username');
56
     * // working with anonymous function
57
     * $fullName = ArrayHelper::getValueByPath($user, function ($user, $defaultValue) {
58
     *     return $user->firstName . ' ' . $user->lastName;
59
     * });
60
     * // using dot format to retrieve the property of embedded object
61
     * $street = \yii\helpers\ArrayHelper::getValue($users, 'address.street');
62
     * // using an array of keys to retrieve the value
63
     * $value = \yii\helpers\ArrayHelper::getValue($versions, ['1.0', 'date']);
64
     * ```
65
     *
66
     * @param array|object $array array or object to extract value from
67
     * @param Closure|string $key key name of the array element, an array of keys or property name of the object,
68
     * or an anonymous function returning the value. The anonymous function signature should be:
69
     * `function($array, $defaultValue)`.
70
     * The possibility to pass an array of keys is available since version 2.0.4.
71
     * @param mixed|null $default the default value to be returned if the specified array key does not exist. Not used when
72
     * getting value from an object.
73
     *
74
     * @return mixed the value of the element if found, default value otherwise
75
     */
76
    public static function getValueByPath(object|array $array, Closure|string $key, mixed $default = null)
77
    {
78
        if ($key instanceof Closure) {
79
            return $key($array, $default);
80
        }
81
82
        if (is_array($key)) {
0 ignored issues
show
introduced by
The condition is_array($key) is always false.
Loading history...
83
            $lastKey = array_pop($key);
84
            foreach ($key as $keyPart) {
85
                $array = static::getValueByPath($array, $keyPart);
86
            }
87
            $key = $lastKey ?? '';
88
        }
89
90
        if (is_object($array) && property_exists($array, $key)) {
0 ignored issues
show
introduced by
The condition is_object($array) is always false.
Loading history...
91
            return $array->$key;
92
        }
93
        if (static::keyExists($key, $array)) {
94
            return $array[$key];
95
        }
96
97
        if ($key && ($pos = strrpos($key, '.')) !== false) {
98
            $array = static::getValueByPath($array, substr($key, 0, $pos), $default);
99
            $key = substr($key, $pos + 1);
100
        }
101
102
        if (is_object($array)) {
103
            // this is expected to fail if the property does not exist, or __get() is not implemented
104
            // it is not reliably possible to check whether a property is accessible beforehand
105
            try {
106
                return $array->$key;
107
            } catch (\Exception $e) {
0 ignored issues
show
Unused Code introduced by
catch (\Exception $e) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
108
                if ($array instanceof ArrayAccess) {
109
                    return $default;
110
                }
111
                throw $e;
112
            }
113
        }
114
115
        if (static::keyExists($key, $array)) {
116
            return $array[$key];
117
        }
118
119
        return $default;
120
    }
121
}
122