Passed
Pull Request — master (#479)
by Def
02:15
created

ArrayHelper::keyExists()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 9
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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