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
ArrayHelper $direction error when anonymous function #17372
Comments
Yes, that's valid. |
@samdark, this example from the documentation is incorrect https://www.yiiframework.com/doc/guide/2.0/en/helper-array
ArrayHelper::multisort($data, function($item) {
return isset($item['age']) ? ['age', 'name'] : 'name';
}); You can't use this function because you need to know sorting keys (the result of this function) before this line https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseArrayHelper.php#L651 Even this example is wrong even if it doesn't generate an error: $data = [
['age' => 30, 'name' => 'Alexander'],
['age' => 19, 'name' => 'Barney'],
['age' => 30, 'name' => 'Brian'],
];
ArrayHelper::multisort($data, function () {
return ['age', 'name'];
}); |
This can be fixed by adding this line: public static function multisort(&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR)
{
$key = $key instanceof \Closure ? call_user_func($key) : $key;
... But, there is a test case which expects that anonymous function will be passed to the public function testMultisortClosure()
{
$changelog = [
'- Enh #123: test1',
'- Bug #125: test2',
'- Bug #123: test2',
'- Enh: test3',
'- Bug: test4',
];
$i = 0;
ArrayHelper::multisort($changelog, function ($line) use (&$i) {
if (preg_match('/^- (Enh|Bug)( #\d+)?: .+$/', $line, $m)) {
$o = ['Bug' => 'C', 'Enh' => 'D'];
return $o[$m[1]] . ' ' . (!empty($m[2]) ? $m[2] : 'AAAA' . $i++);
}
return 'B' . $i++;
}, SORT_ASC, SORT_NATURAL);
$this->assertEquals([
'- Bug #123: test2',
'- Bug #125: test2',
'- Bug: test4',
'- Enh #123: test1',
'- Enh: test3',
], $changelog);
} This is a conflict of different behaviors that anonymous function should have. /*
* @param string|\Closure|array $key the key(s) to be sorted by. This refers to a key name of the sub-array
* elements, a property name of the objects, or an anonymous function returning the values for comparison
* purpose. The anonymous function signature should be: `function($item)`.
* To sort by multiple keys, provide an array of keys here.
*/ It says that function should return values for comparison, not keys. Example in the docs should be something like this: $data = [
['age' => 30, 'name' => 'Alexander'],
['age' => 19, 'name' => 'Barney'],
['age' => 30, 'name' => 'Brian'],
];
ArrayHelper::multisort($data, function ($item) {
return isset($item['age']) ? $item['age'] : $item['name'];
}, SORT_DESC); But you can sort only by one field in this case. |
What steps will reproduce the problem?
What is the expected result?
sorted array
What do you get instead?
The text was updated successfully, but these errors were encountered: