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

ArrayHelper   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 81
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 11
eloc 20
c 2
b 0
f 0
dl 0
loc 81
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B getValueByPath() 0 39 11
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
        /** @psalm-var array<string, mixed> $array */
66
        if (array_key_exists($key, $array)) {
67
            return $array[$key];
68
        }
69
70
        if ($key && ($pos = strrpos($key, '.')) !== false) {
71
            /** @psalm-var array<string, mixed>|object $array */
72
            $array = static::getValueByPath($array, substr($key, 0, $pos), $default);
73
            $key = substr($key, $pos + 1);
74
        }
75
76
        if (is_object($array)) {
77
            // this is expected to fail if the property does not exist, or __get() is not implemented
78
            // it is not reliably possible to check whether a property is accessible beforehand
79
            try {
80
                return $array->$key;
81
            } 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...
82
                if ($array instanceof ArrayAccess) {
83
                    return $default;
84
                }
85
                throw $e;
86
            }
87
        }
88
89
        if (array_key_exists($key, $array)) {
90
            return $array[$key];
91
        }
92
93
        return $default;
94
    }
95
}
96