Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get array value by matcher #135

Open
yus-ham opened this issue Aug 30, 2023 · 1 comment · May be fixed by #142
Open

Get array value by matcher #135

yus-ham opened this issue Aug 30, 2023 · 1 comment · May be fixed by #142
Labels
status:ready for adoption Feel free to implement this issue.

Comments

@yus-ham
Copy link

yus-ham commented Aug 30, 2023

What the problem?

arrays/src/ArrayHelper.php

Lines 210 to 212 in c3d14a3

if ($key instanceof Closure) {
return $key($array, $default);
}

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

arrays/src/ArrayHelper.php

Lines 184 to 188 in c3d14a3

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

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
Copy link
Member

vjik commented Aug 30, 2023

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;

@samdark samdark added the status:ready for adoption Feel free to implement this issue. label Sep 3, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
status:ready for adoption Feel free to implement this issue.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants