yiisoft / arrays

Yii Array Helper
https://www.yiiframework.com/
BSD 3-Clause "New" or "Revised" License
52 stars 28 forks source link

Get array value by matcher #135

Open yus-ham opened 1 year ago

yus-ham commented 1 year ago

What the problem?

https://github.com/yiisoft/arrays/blob/c3d14a3dea93edd44759de57105f02f18c135cad/src/ArrayHelper.php#L210-L212

Current implementation of getValue($array, $key) with $key as anonymous function is not match with the phrases Retrieves the value of an array element. basically it just like a value transformation, it can returns anything even value from outside array itself as of in example https://github.com/yiisoft/arrays/blob/c3d14a3dea93edd44759de57105f02f18c135cad/src/ArrayHelper.php#L184-L188

What is the expected result?

the implementation should search value of an array by matcher function

    if ($key instanceof Closure) {
        foreach ($array as $key => $value) {
            if ($key($value, $key)) {
                return $value;
            }
        }

        return $default;
    }

and then, change the signature of matcher function to be function($value, $key): bool .

Additional info

Q A
Version 1.0.?
PHP version
Operating system
vjik commented 1 year ago

Looks good for me. Instead of code:

$fullName = \Yiisoft\Arrays\ArrayHelper::getValue($user, function ($user, $defaultValue) { 
    return $user->firstName . ' ' . $user->lastName; 
});

we can use:

$fullName = $user->firstName . ' ' . $user->lastName;