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

ArrayHelper::getValueByPath()   C

Complexity

Conditions 12
Paths 9

Size

Total Lines 38
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 19
c 2
b 1
f 0
dl 0
loc 38
rs 6.9666
cc 12
nc 9
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
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
     * Retrieves the value of an array element or object property with the given key or property name.
17
     * If the key does not exist in the array, the default value will be returned instead.
18
     * Not used when getting value from an object.
19
     *
20
     * The key may be specified in a dot format to retrieve the value of a sub-array or the property
21
     * of an embedded object. In particular, if the key is `x.y.z`, then the returned value would
22
     * be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']`
23
     * or `$array->x` is neither an array nor an object, the default value will be returned.
24
     * Note that if the array already has an element `x.y.z`, then its value will be returned
25
     * instead of going through the sub-arrays. So it is better to be done specifying an array of key names
26
     * like `['x', 'y', 'z']`.
27
     *
28
     * Below are some usage examples,
29
     *
30
     * ```php
31
     * // working with array
32
     * $username = ArrayHelper::getValueByPath($_POST, 'username');
33
     * // working with object
34
     * $username = ArrayHelper::getValueByPath($user, 'username');
35
     * // working with anonymous function
36
     * $fullName = ArrayHelper::getValueByPath($user, function ($user, $defaultValue) {
37
     *     return $user->firstName . ' ' . $user->lastName;
38
     * });
39
     * // using dot format to retrieve the property of embedded object
40
     * $street = \yii\helpers\ArrayHelper::getValue($users, 'address.street');
41
     * // using an array of keys to retrieve the value
42
     * $value = \yii\helpers\ArrayHelper::getValue($versions, ['1.0', 'date']);
43
     * ```
44
     *
45
     * @param array|object $array array or object to extract value from
46
     * @param Closure|string $key key name of the array element, an array of keys or property name of the object,
47
     * or an anonymous function returning the value. The anonymous function signature should be:
48
     * `function($array, $defaultValue)`.
49
     * The possibility to pass an array of keys is available since version 2.0.4.
50
     * @param mixed|null $default the default value to be returned if the specified array key does not exist. Not used when
51
     * getting value from an object.
52
     *
53
     * @return mixed the value of the element if found, default value otherwise
54
     */
55
    public static function getValueByPath(object|array $array, Closure|string $key, mixed $default = null)
56
    {
57
        if ($key instanceof Closure) {
58
            return $key($array, $default);
59
        }
60
61
        if (is_object($array) && property_exists($array, $key)) {
0 ignored issues
show
introduced by
The condition is_object($array) is always false.
Loading history...
62
            return $array->$key;
63
        }
64
65
        if (is_array($array) && array_key_exists($key, $array)) {
66
            return $array[$key];
67
        }
68
69
        if ($key && ($pos = strrpos($key, '.')) !== false) {
70
            /** @psalm-var array<string, mixed>|object $array */
71
            $array = static::getValueByPath($array, substr($key, 0, $pos), $default);
72
            $key = substr($key, $pos + 1);
73
        }
74
75
        if (is_object($array)) {
76
            // this is expected to fail if the property does not exist, or __get() is not implemented
77
            // it is not reliably possible to check whether a property is accessible beforehand
78
            try {
79
                return $array->$key;
80
            } 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...
81
                if ($array instanceof ArrayAccess) {
82
                    return $default;
83
                }
84
                throw $e;
85
            }
86
        }
87
88
        if (array_key_exists($key, $array)) {
89
            return $array[$key];
90
        }
91
92
        return $default;
93
    }
94
}
95